Compare commits
2
Commits
c11df75225
...
106ac2ff0f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
106ac2ff0f | ||
|
|
6bfa4294cc |
No files matched your search
+14
-7
@@ -467,10 +467,13 @@ BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
|
||||
SetKeepAliveOptions(m_sClientSocket);
|
||||
#endif
|
||||
}
|
||||
#ifdef _WIN32
|
||||
#ifdef YAMA_TLS_CHANNEL
|
||||
// 单向 TLS:证书存在(TlsEnabled())时,在应用协议首包前完成握手;握手失败即断开,
|
||||
// 不回退明文(fail-closed,防降级)。证书存在但加载失败(TlsLoadError())同样拒绝
|
||||
// 连接。握手须在 m_bConnected 置位前,确保工作线程不会在握手尚未完成时就开始 recv。
|
||||
// m_useTls 在这里一次性锁定:Linux 客户端可能在此后收到服务端下发并热切换传输方式,
|
||||
// 那条连接已建立,本连接的 Send/Recv 必须继续按握手时的传输方式走。
|
||||
m_useTls = false;
|
||||
if (TlsLoadError()) {
|
||||
Mprintf("[TLS] 证书加载失败,拒绝连接(fail-closed)\n");
|
||||
closesocket(m_sClientSocket);
|
||||
@@ -484,6 +487,7 @@ BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
|
||||
m_sClientSocket = INVALID_SOCKET;
|
||||
return FALSE;
|
||||
}
|
||||
m_useTls = true;
|
||||
}
|
||||
#endif
|
||||
m_bConnected = TRUE;
|
||||
@@ -549,9 +553,9 @@ DWORD WINAPI IOCPClient::WorkThreadProc(LPVOID lParam)
|
||||
Sleep(50);
|
||||
continue;
|
||||
}
|
||||
#ifdef _WIN32
|
||||
#ifdef YAMA_TLS_CHANNEL
|
||||
// TLS 会话里可能有已解密、尚未交付的明文(select 只看底层 socket,看不到
|
||||
// Schannel 内部缓冲),优先消费,避免被 select 卡住。
|
||||
// TLS 库内部缓冲),优先消费,避免被 select 卡住。
|
||||
if (This->HasPendingData()) {
|
||||
if (!This->ProcessRecvData(&m_CompressedBuffer, szBuffer, MAX_RECV_BUFFER - 1, 0)) {
|
||||
break;
|
||||
@@ -665,11 +669,11 @@ 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());
|
||||
#ifdef YAMA_TLS_CHANNEL
|
||||
Mprintf("[ERROR] Unknown header! this=%p bufLen=%lu, first 16 bytes: %s (useTls=%d tlsReady=%d)\n",
|
||||
this, bufLen, buf.c_str(), (int)m_useTls, (int)m_tls.IsReady());
|
||||
#else
|
||||
// 非 Windows 平台没有 TlsChannel(TLS 只在 Windows 客户端实现)
|
||||
// macOS/Android 没有 TlsChannel(TLS 只在这两个平台之外的客户端实现)
|
||||
Mprintf("[ERROR] Unknown header! this=%p bufLen=%lu, first 16 bytes: %s\n",
|
||||
this, bufLen, buf.c_str());
|
||||
#endif
|
||||
@@ -901,6 +905,9 @@ VOID IOCPClient::Disconnect()
|
||||
closesocket(m_sClientSocket);
|
||||
m_sClientSocket = INVALID_SOCKET;
|
||||
|
||||
#ifdef YAMA_TLS_CHANNEL
|
||||
m_useTls = false; // 连接已断,Send/Recv 回到明文路径(下次 ConnectServer 重新锁定)
|
||||
#endif
|
||||
m_bConnected = FALSE;
|
||||
}
|
||||
|
||||
|
||||
+17
-9
@@ -8,10 +8,13 @@
|
||||
#include "stdafx.h"
|
||||
#include <WinSock2.h>
|
||||
#include <MSTcpIP.h>
|
||||
#include "TlsChannel.h"
|
||||
#pragma comment(lib,"ws2_32.lib")
|
||||
#endif
|
||||
|
||||
// TLS 通道:Windows 走 Schannel,Linux 走 OpenSSL;macOS/Android 下该头为空,
|
||||
// 且不定义 YAMA_TLS_CHANNEL,下方代码自动退回明文。
|
||||
#include "TlsChannel.h"
|
||||
|
||||
#include "Buffer.h"
|
||||
#include "zstd/zstd.h"
|
||||
#include "domain_pool.h"
|
||||
@@ -290,8 +293,8 @@ public:
|
||||
protected:
|
||||
virtual int ReceiveData(char* buffer, int bufSize, int flags)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
if (TlsEnabled())
|
||||
#ifdef YAMA_TLS_CHANNEL
|
||||
if (m_useTls)
|
||||
return m_tls.Recv(m_sClientSocket, buffer, bufSize - 1);
|
||||
#endif
|
||||
// TCP版本调用 recv
|
||||
@@ -301,18 +304,18 @@ protected:
|
||||
virtual bool ProcessRecvData(CBuffer* m_CompressedBuffer, char* szBuffer, int len, int flag);
|
||||
virtual int SendTo(const char* buf, int len, int flags)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
if (TlsEnabled())
|
||||
#ifdef YAMA_TLS_CHANNEL
|
||||
if (m_useTls)
|
||||
return m_tls.Send(m_sClientSocket, buf, len);
|
||||
#endif
|
||||
return ::send(m_sClientSocket, buf, len, flags);
|
||||
}
|
||||
// TLS 会话里可能有已解密但尚未交付的明文(select 只能看到底层 socket 可读性,
|
||||
// 看不到 Schannel 内部缓冲),接收线程在 select 前须优先消费,避免其被卡住。
|
||||
// 看不到 TLS 库内部缓冲),接收线程在 select 前须优先消费,避免其被卡住。
|
||||
bool HasPendingData() const
|
||||
{
|
||||
#ifdef _WIN32
|
||||
return m_tls.HasPending();
|
||||
#ifdef YAMA_TLS_CHANNEL
|
||||
return m_useTls && m_tls.HasPending();
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
@@ -325,8 +328,13 @@ protected:
|
||||
protected:
|
||||
sockaddr_in m_ServerAddr;
|
||||
SOCKET m_sClientSocket;
|
||||
#ifdef _WIN32
|
||||
#ifdef YAMA_TLS_CHANNEL
|
||||
TlsChannel m_tls; // TLS 会话(证书存在时才启用,见 TlsChannel.h)
|
||||
// 本连接是否走 TLS:在 ConnectServer 里握手成功时置位、Disconnect 时清除,Send/Recv
|
||||
// 一律按这个快照走,不再每次现查 TlsEnabled()。Linux 客户端支持服务端下发后热切换
|
||||
// 传输方式(TlsReload),若现查全局开关,切换后到重连完成之间的这一秒里会把明文塞进
|
||||
// 已建立的 TLS 会话(或反过来),白白制造协议错误。
|
||||
bool m_useTls = false;
|
||||
#endif
|
||||
BOOL m_bWorkThread;
|
||||
HANDLE m_hWorkThread;
|
||||
|
||||
+95
-15
@@ -1,25 +1,29 @@
|
||||
// TlsChannel.h — Windows 客户端单向 TLS(Schannel)会话封装
|
||||
// TlsChannel.h — 客户端单向 TLS 会话封装(Windows: Schannel;Linux: OpenSSL)
|
||||
//
|
||||
// 用途:为 YAMA 客户端(被控端)提供「按需开启」的传输层加密。当信任锚证书存在时
|
||||
// (注册表 Software\<exehash>\settings\tls_cert,或 yama-ca.pem 文件,见 TlsChannel.cpp
|
||||
// 的 InitTls),所有出站 TCP 连接在应用协议首包前先完成 TLS 握手;握手失败一律断开
|
||||
// 用途:为 YAMA 客户端(被控端)提供「按需开启」的传输层加密。当信任锚证书存在时,
|
||||
// 所有出站 TCP 连接在应用协议首包前先完成 TLS 握手;握手失败一律断开
|
||||
// (fail-closed,不回退明文)。
|
||||
//
|
||||
// 选型:Schannel(Windows 原生 SSPI),零第三方依赖;secur32.lib / crypt32.lib 为
|
||||
// 系统库。单向 TLS:客户端只校验服务端证书链到固定的信任锚,不提供客户端证书,
|
||||
// 客户端身份仍由隧道内登录(V1 PwdHmac / V2 ECDSA)承担。
|
||||
// 选型:
|
||||
// - Windows:Schannel(原生 SSPI),零第三方依赖;secur32.lib / crypt32.lib 为系统库。
|
||||
// - Linux:OpenSSL(构建链已因 libsign 链接 libcrypto,另加 libssl 即可)。
|
||||
// 两者都是单向 TLS:客户端只校验服务端证书链到固定的信任锚,不提供客户端证书,
|
||||
// 客户端身份仍由隧道内登录(V1 PwdHmac / V2 ECDSA)承担;均不校主机名(客户端按 IP
|
||||
// 连接),不做吊销检查——与 Windows 版既有语义保持一致。
|
||||
//
|
||||
// 线程模型:Handshake 在连接建立线程上、m_bConnected 置位前调用;Send/Recv 分别在
|
||||
// 发送线程 / 接收线程上调用。上下文生命周期(Handshake/CloseHandles 释放 m_ctx)与
|
||||
// Send/Recv 对 m_ctx 的使用(EncryptMessage/DecryptMessage)由 m_ctxMtx 互斥,避免
|
||||
// 重连线程释放上下文时与使用线程产生 use-after-free。本对象作为 IOCPClient 的值成员
|
||||
// 存在,析构时释放上下文。
|
||||
// 发送线程 / 接收线程上调用。上下文生命周期(Handshake/CloseHandles 释放上下文)与
|
||||
// Send/Recv 对上下文的使用由 m_ctxMtx 互斥,避免重连线程释放上下文时与使用线程产生
|
||||
// use-after-free。本对象作为 IOCPClient 的值成员存在,析构时释放上下文。
|
||||
//
|
||||
// 注意:本文件仅在 _WIN32 下有效,非 Windows 构建(Linux/macOS/Android)不含任何内容,
|
||||
// 客户端维持明文(TLS 接入按设计文档延后)。
|
||||
// 平台范围:_WIN32 与 Linux(非 Android)有实现;macOS / Android 不含任何内容,客户端
|
||||
// 维持明文(TLS 接入按设计文档延后)。两平台都通过 YAMA_TLS_CHANNEL 宏告知调用方
|
||||
// 「本平台有 TLS 通道」。
|
||||
#pragma once
|
||||
|
||||
#ifdef _WIN32
|
||||
#if defined(_WIN32)
|
||||
|
||||
#define YAMA_TLS_CHANNEL 1
|
||||
|
||||
#include <WinSock2.h>
|
||||
|
||||
@@ -91,4 +95,80 @@ private:
|
||||
std::vector<BYTE> m_pending; // 已解密、未交付给应用层的明文
|
||||
};
|
||||
|
||||
#endif // _WIN32
|
||||
#elif defined(__linux__) && !defined(__ANDROID__)
|
||||
|
||||
#define YAMA_TLS_CHANNEL 1
|
||||
|
||||
#include <string>
|
||||
#include <mutex>
|
||||
|
||||
struct ssl_st; // OpenSSL 的 SSL 类型,避免头文件把 openssl/ssl.h 拖进所有翻译单元
|
||||
|
||||
// 进程级 TLS 开关:首次调用时加载信任锚文件,返回是否启用。线程安全、幂等。
|
||||
// Linux 版是「可热切换」的:TlsReload() 之后本函数立刻反映新状态(不是 call_once)。
|
||||
bool TlsEnabled();
|
||||
|
||||
// 信任锚已配置但加载失败(无法读取/格式错误/内容为空)时为 true:客户端必须拒绝连接
|
||||
// (fail-closed),不得静默回退明文。线程安全、幂等。
|
||||
bool TlsLoadError();
|
||||
|
||||
// 服务端下发信任锚(COMMAND_TLS_ENABLE):把 PEM 正文写入
|
||||
// $XDG_CONFIG_HOME/ghost/yama-ca.pem(默认 ~/.config/ghost/yama-ca.pem,无 HOME 时退回
|
||||
// 程序目录),原子替换、权限 0600。写入前先解析验证,不是合法证书就整包拒绝。
|
||||
// 落盘后用 TlsReload() 立即生效(Windows 客户端仍要重启进程)。
|
||||
bool TlsTrustAnchorSave(const std::string& pem, std::string& err);
|
||||
|
||||
// 服务端撤销信任锚(COMMAND_TLS_DISABLE):删除上述配置文件(含程序目录同名文件)。
|
||||
// 返回是否删掉了至少一个文件;之后同样用 TlsReload() 立即生效。
|
||||
bool TlsTrustAnchorRemove(std::string& err);
|
||||
|
||||
// 按当前信任锚文件重建 TLS 上下文并更新开关,让随后建立的新连接立刻走新传输方式
|
||||
// (已建立的连接不受影响:SSL 对象自持 SSL_CTX 引用)。信任锚无效时不做任何改动、
|
||||
// 返回 false 并给出原因——一次坏下发不该把正在工作的客户端打死(下次启动仍 fail-closed)。
|
||||
// 线程安全:与 TlsEnabled/TlsLoadError/Handshake 互斥。
|
||||
bool TlsReload(std::string& err);
|
||||
|
||||
class TlsChannel
|
||||
{
|
||||
public:
|
||||
TlsChannel() {}
|
||||
~TlsChannel() { CloseHandles(); }
|
||||
|
||||
// 持 SSL*,禁止拷贝/赋值(避免上下文被二次释放)。
|
||||
TlsChannel(const TlsChannel&) = delete;
|
||||
TlsChannel& operator=(const TlsChannel&) = delete;
|
||||
|
||||
// 在已连通的 socket 上完成 TLS 1.2 客户端握手并按信任锚校验服务端证书链。失败返回
|
||||
// false,调用方必须关闭 socket(fail-closed)。可重复调用(重连时复用同一对象)。
|
||||
bool Handshake(int sock);
|
||||
|
||||
// 解密读取:返回 >0 的明文字节数;0 表示对端正常关闭;SOCKET_ERROR(-1) 出错。
|
||||
int Recv(int sock, char* buf, int len);
|
||||
|
||||
// 加密发送 len 字节:成功返回已完整发送的明文字节数(== len);失败返回已发送的
|
||||
// 前缀字节数(>0)或 SOCKET_ERROR(一个字节都没发出去时)。
|
||||
int Send(int sock, const char* buf, int len);
|
||||
|
||||
// 是否有待交付的数据(SSL 内部已缓冲)供接收线程在 select 前优先消费。OpenSSL 会在
|
||||
// 一个 TLS 记录里装多条应用数据,一次 SSL_read 只交付一部分;剩余的留在 SSL 内部,
|
||||
// select 看不到,必须用 SSL_has_pending() 才能避免被 2 秒超时卡住。
|
||||
bool HasPending() const;
|
||||
|
||||
// 握手是否已完成(Send/Recv 可用)。诊断用:区分「本连接已走 TLS」与「裸连接」。
|
||||
bool IsReady() const { return m_ready; }
|
||||
|
||||
private:
|
||||
void CloseHandles();
|
||||
|
||||
ssl_st* m_ssl = nullptr;
|
||||
int m_fd = -1;
|
||||
bool m_ready = false; // 握手完成,Send/Recv 可用
|
||||
|
||||
// 保护上下文生命周期:重连线程的 Handshake/CloseHandles(释放 m_ssl)与工作线程的
|
||||
// Recv(SSL_read)、发送线程的 Send(SSL_write)互斥。OpenSSL 的 SSL 对象不允许
|
||||
// 并发使用,所以 Send/Recv 也持锁——与 Windows 版同样式。
|
||||
// mutable 是因为 HasPending() 是 const 但需要持锁读 m_ssl。
|
||||
mutable std::recursive_mutex m_ctxMtx;
|
||||
};
|
||||
|
||||
#endif // _WIN32 / __linux__ && !__ANDROID__
|
||||
@@ -0,0 +1,559 @@
|
||||
// TlsChannelLinux.cpp — 见 TlsChannel.h 头注释。仅 Linux(非 Android)编译。
|
||||
//
|
||||
// 与 Windows 的 Schannel 实现语义对齐:
|
||||
// - 单向 TLS 1.2(min=max=1.2,与 SP_PROT_TLS1_2_CLIENT 及两套服务端一致);
|
||||
// - 信任锚严格钉扎:证书链只按信任锚文件里的证书校验,不含系统根库;
|
||||
// - 不校主机名(客户端按 IP 连接,与 Windows 版一致)、不做吊销检查;
|
||||
// - 信任锚「存在即已配置」:读取/解析失败一律 TlsLoadError()=true → 调用方拒绝连接。
|
||||
//
|
||||
// 与 Windows 实现的差异:OpenSSL 自己管理 TLS 记录缓冲,不需要 m_raw/m_pending;
|
||||
// 一次性交付不出去的明文留在 SSL 内部,由 SSL_has_pending()/SSL_pending() 暴露给
|
||||
// 接收线程在 select 前优先消费。
|
||||
#if defined(__linux__) && !defined(__ANDROID__)
|
||||
|
||||
#include "TlsChannel.h"
|
||||
|
||||
#include "common/commands.h" // SOCKET_ERROR / closesocket 等 POSIX 兼容宏
|
||||
#include "common/logger.h" // Mprintf
|
||||
|
||||
#include <openssl/err.h>
|
||||
#include <openssl/pem.h>
|
||||
#include <openssl/ssl.h>
|
||||
#include <openssl/x509.h>
|
||||
#include <openssl/x509_vfy.h>
|
||||
|
||||
#include <cerrno>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace {
|
||||
|
||||
const char* const kAnchorName = "yama-ca.pem";
|
||||
|
||||
// 进程级 TLS 状态。与 Windows 版的 call_once 不同,这里可由 TlsReload() 热切换
|
||||
// (服务端 COMMAND_TLS_ENABLE/DISABLE 落盘后立即重建),因此用互斥量而不是 once_flag。
|
||||
std::mutex g_stateMtx; // 保护下面四项
|
||||
bool g_inited = false; // 首次加载已完成(含 fail-closed 基态)
|
||||
bool g_tlsEnabled = false; // TLS 会话可用:send/recv 走加密
|
||||
bool g_tlsError = false; // 信任锚存在但加载失败:拒绝连接(fail-closed)
|
||||
SSL_CTX* g_tlsCtx = nullptr; // 进程级上下文(线程安全,可被多条连接共享)
|
||||
std::string g_anchorPath; // 仅用于日志
|
||||
|
||||
// 配置目录:与 LinuxConfig 相同规则($XDG_CONFIG_HOME/ghost 或 ~/.config/ghost)。
|
||||
std::string ConfigDir()
|
||||
{
|
||||
const char* xdg = getenv("XDG_CONFIG_HOME");
|
||||
if (xdg && xdg[0])
|
||||
return std::string(xdg) + "/ghost";
|
||||
const char* home = getenv("HOME");
|
||||
if (!home || !home[0])
|
||||
return std::string();
|
||||
return std::string(home) + "/.config/ghost";
|
||||
}
|
||||
|
||||
// 可执行文件所在目录(readlink /proc/self/exe,失败返回空)。
|
||||
std::string ExeDir()
|
||||
{
|
||||
char buf[4096];
|
||||
ssize_t n = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
|
||||
if (n <= 0)
|
||||
return std::string();
|
||||
buf[n] = '\0';
|
||||
char* slash = strrchr(buf, '/');
|
||||
if (!slash)
|
||||
return std::string();
|
||||
*slash = '\0';
|
||||
return std::string(buf);
|
||||
}
|
||||
|
||||
// 信任锚候选路径(按优先级),只返回已经存在的那个:
|
||||
// 1) $XDG_CONFIG_HOME/ghost/yama-ca.pem(默认 ~/.config/ghost/yama-ca.pem)
|
||||
// 2) 可执行文件同目录 yama-ca.pem(兼容手工投递,与 Windows 的 exe 同名文件回退一致)
|
||||
bool FindAnchorPath(std::string& out)
|
||||
{
|
||||
std::vector<std::string> cands;
|
||||
std::string dir = ConfigDir();
|
||||
if (!dir.empty())
|
||||
cands.push_back(dir + "/" + kAnchorName);
|
||||
std::string exed = ExeDir();
|
||||
if (!exed.empty())
|
||||
cands.push_back(exed + "/" + kAnchorName);
|
||||
for (size_t i = 0; i < cands.size(); ++i) {
|
||||
if (access(cands[i].c_str(), F_OK) == 0) {
|
||||
out = cands[i];
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// 递归 mkdir -p(已存在视为成功)。
|
||||
bool MkdirP(const std::string& path, mode_t mode)
|
||||
{
|
||||
if (path.empty())
|
||||
return false;
|
||||
struct stat st;
|
||||
if (stat(path.c_str(), &st) == 0)
|
||||
return S_ISDIR(st.st_mode);
|
||||
size_t slash = path.find_last_of('/');
|
||||
if (slash != std::string::npos && slash > 0) {
|
||||
if (!MkdirP(path.substr(0, slash), mode))
|
||||
return false;
|
||||
}
|
||||
if (mkdir(path.c_str(), mode) != 0 && errno != EEXIST)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// 把 PEM(可含多张证书)或 DER 信任锚写入 store。返回加入的证书数。
|
||||
int LoadAnchors(const std::string& data, X509_STORE* store)
|
||||
{
|
||||
int added = 0;
|
||||
if (data.find("-----BEGIN") != std::string::npos) {
|
||||
BIO* bio = BIO_new_mem_buf(data.data(), (int)data.size());
|
||||
if (bio) {
|
||||
for (;;) {
|
||||
X509* cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
|
||||
if (!cert)
|
||||
break;
|
||||
if (X509_STORE_add_cert(store, cert) == 1)
|
||||
++added;
|
||||
else
|
||||
ERR_clear_error(); // 重复证书等:忽略该张,继续读后面的
|
||||
X509_free(cert);
|
||||
}
|
||||
BIO_free(bio);
|
||||
}
|
||||
ERR_clear_error();
|
||||
}
|
||||
if (added == 0) {
|
||||
// 退回 DER(单张)
|
||||
const unsigned char* p = (const unsigned char*)data.data();
|
||||
X509* cert = d2i_X509(NULL, &p, (long)data.size());
|
||||
if (cert) {
|
||||
if (X509_STORE_add_cert(store, cert) == 1)
|
||||
++added;
|
||||
else
|
||||
ERR_clear_error();
|
||||
X509_free(cert);
|
||||
}
|
||||
ERR_clear_error();
|
||||
}
|
||||
return added;
|
||||
}
|
||||
|
||||
enum BuildResult
|
||||
{
|
||||
BUILD_PLAINTEXT, // 没有信任锚文件 → 明文模式
|
||||
BUILD_READY, // *outCtx 为新建上下文,调用方接管所有权
|
||||
BUILD_INVALID, // 文件存在但读不了/解析不出证书(err 说明原因)
|
||||
};
|
||||
|
||||
// 按当前信任锚文件构建一份新的 TLS 上下文。不读写任何全局状态,便于「先构建、成功再替换」。
|
||||
BuildResult BuildState(SSL_CTX** outCtx, std::string& anchorPath, std::string& err, int& certs)
|
||||
{
|
||||
*outCtx = nullptr;
|
||||
certs = 0;
|
||||
anchorPath.clear();
|
||||
|
||||
std::string path;
|
||||
if (!FindAnchorPath(path)) {
|
||||
// 无证书 → 明文(默认,与老客户端一致)
|
||||
return BUILD_PLAINTEXT;
|
||||
}
|
||||
anchorPath = path;
|
||||
|
||||
// 证书已配置:管理员已「颁发」,必须走 TLS;读取/解析失败即拒绝连接(fail-closed),
|
||||
// 不能静默回退明文。
|
||||
std::ifstream f(path.c_str(), std::ios::binary);
|
||||
if (!f) {
|
||||
err = "cannot open " + path + ": " + strerror(errno);
|
||||
return BUILD_INVALID;
|
||||
}
|
||||
std::string pem((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
|
||||
|
||||
SSL_CTX* ctx = SSL_CTX_new(TLS_client_method());
|
||||
if (!ctx) {
|
||||
err = "SSL_CTX_new failed";
|
||||
return BUILD_INVALID;
|
||||
}
|
||||
|
||||
// TLS 1.2 钉扎:与 Windows 客户端(SP_PROT_TLS1_2_CLIENT)及两套服务端(Schannel
|
||||
// SP_PROT_TLS1_2_SERVER / Go MinVersion=TLS1.2)保持一致。
|
||||
SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
|
||||
SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION);
|
||||
|
||||
// SSL_VERIFY_PEER + 自定义 store = 严格钉扎到信任锚(不含系统根库),链校验在握手内
|
||||
// 完成,失败即握手失败。verify 回调传 NULL 使用默认行为(只验链,不校主机名)。
|
||||
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
|
||||
SSL_CTX_set_verify_depth(ctx, 8);
|
||||
|
||||
// 对端不打招呼就断开(不发 close_notify)在这里是常态:服务端关闭子连接时不发,
|
||||
// 客户端自己也同样不发(见 CloseHandles 的说明)。OpenSSL 3.0 起这种 unexpected EOF
|
||||
// 被归为 SSL_ERROR_SSL 协议错误,于是每结束一个终端/文件传输子连接都会记一条
|
||||
// 「SSL_read failed」——线上日志看着像 TLS 坏了。打开这个选项让它按正常关闭处理
|
||||
// (SSL_read 返回 0),与 Recv 的文档语义以及 Windows 版的行为一致。
|
||||
#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
|
||||
SSL_CTX_set_options(ctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
|
||||
#endif
|
||||
|
||||
X509_STORE* store = X509_STORE_new();
|
||||
certs = store ? LoadAnchors(pem, store) : 0;
|
||||
if (!store || certs <= 0) {
|
||||
if (store)
|
||||
X509_STORE_free(store);
|
||||
SSL_CTX_free(ctx);
|
||||
certs = 0;
|
||||
err = "trust anchor " + path + " present but empty/invalid";
|
||||
return BUILD_INVALID;
|
||||
}
|
||||
SSL_CTX_set_cert_store(ctx, store); // ctx 接管 store 所有权
|
||||
|
||||
*outCtx = ctx;
|
||||
return BUILD_READY;
|
||||
}
|
||||
|
||||
// 替换全局状态并释放旧上下文(调用方持 g_stateMtx)。SSL 对象在 SSL_new 时已递增
|
||||
// SSL_CTX 的引用计数,所以已经建立的连接不会因为这里释放旧 ctx 而失效。
|
||||
void InstallStateLocked(SSL_CTX* ctx, bool enabled, bool error, const std::string& anchor)
|
||||
{
|
||||
SSL_CTX* old = g_tlsCtx;
|
||||
g_tlsCtx = ctx;
|
||||
g_tlsEnabled = enabled;
|
||||
g_tlsError = error;
|
||||
g_anchorPath = anchor;
|
||||
if (old)
|
||||
SSL_CTX_free(old);
|
||||
}
|
||||
|
||||
// 首次加载(调用方持锁):锚存在但无效时置 fail-closed。
|
||||
void EnsureInitLocked()
|
||||
{
|
||||
if (g_inited)
|
||||
return;
|
||||
g_inited = true;
|
||||
|
||||
SSL_CTX* ctx = nullptr;
|
||||
std::string anchor, err;
|
||||
int certs = 0;
|
||||
switch (BuildState(&ctx, anchor, err, certs)) {
|
||||
case BUILD_PLAINTEXT:
|
||||
InstallStateLocked(nullptr, false, false, anchor);
|
||||
Mprintf("[TLS] disabled: no trust anchor configured, plaintext mode\n");
|
||||
break;
|
||||
case BUILD_READY:
|
||||
InstallStateLocked(ctx, true, false, anchor);
|
||||
Mprintf("[TLS] enabled: trust anchor loaded (%s, %d cert(s)), all connections use TLS\n",
|
||||
anchor.c_str(), certs);
|
||||
break;
|
||||
case BUILD_INVALID:
|
||||
InstallStateLocked(nullptr, false, true, anchor);
|
||||
Mprintf("[TLS] FATAL: %s; refusing connections (fail-closed)\n", err.c_str());
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool TlsEnabled()
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_stateMtx);
|
||||
EnsureInitLocked();
|
||||
return g_tlsEnabled;
|
||||
}
|
||||
|
||||
bool TlsLoadError()
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_stateMtx);
|
||||
EnsureInitLocked();
|
||||
return g_tlsError;
|
||||
}
|
||||
|
||||
bool TlsReload(std::string& err)
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_stateMtx);
|
||||
EnsureInitLocked(); // 未初始化就先按启动语义建立基态,保持 fail-closed 行为
|
||||
|
||||
SSL_CTX* ctx = nullptr;
|
||||
std::string anchor;
|
||||
int certs = 0;
|
||||
BuildResult r = BuildState(&ctx, anchor, err, certs);
|
||||
if (r == BUILD_INVALID) {
|
||||
// 保留原状态:一次坏下发不该让正在工作的客户端失联(下次启动仍会 fail-closed)。
|
||||
Mprintf("[TLS] reload FAILED: %s; keeping current transport (%s)\n",
|
||||
err.c_str(), g_tlsEnabled ? "TLS" : "plaintext");
|
||||
return false;
|
||||
}
|
||||
if (r == BUILD_PLAINTEXT) {
|
||||
InstallStateLocked(nullptr, false, false, anchor);
|
||||
Mprintf("[TLS] reloaded: no trust anchor, transport is now plaintext\n");
|
||||
return true;
|
||||
}
|
||||
InstallStateLocked(ctx, true, false, anchor);
|
||||
Mprintf("[TLS] reloaded: trust anchor %s (%d cert(s)), transport is now TLS\n",
|
||||
anchor.c_str(), certs);
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---- 信任锚下发 / 撤销(服务端 COMMAND_TLS_ENABLE / COMMAND_TLS_DISABLE)----
|
||||
|
||||
bool TlsTrustAnchorSave(const std::string& pem, std::string& err)
|
||||
{
|
||||
if (pem.empty()) {
|
||||
err = "empty certificate payload";
|
||||
return false;
|
||||
}
|
||||
|
||||
// 先验证再落盘:文件一旦写进去,下次启动就会被无条件信任,坏锚等于把客户端锁死
|
||||
// (fail-closed 连不上,也没法再从服务端改回来)。宁可拒绝一次下发。
|
||||
{
|
||||
X509_STORE* probe = X509_STORE_new();
|
||||
int n = probe ? LoadAnchors(pem, probe) : 0;
|
||||
if (probe)
|
||||
X509_STORE_free(probe);
|
||||
if (n <= 0) {
|
||||
err = "payload is not a valid PEM/DER certificate";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
std::string dir = ConfigDir();
|
||||
if (dir.empty()) {
|
||||
dir = ExeDir(); // 无 HOME 的极端环境:退回程序目录
|
||||
if (dir.empty()) {
|
||||
err = "cannot resolve config directory";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (!MkdirP(dir, 0700)) {
|
||||
err = "cannot create directory " + dir + ": " + strerror(errno);
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string path = dir + "/" + kAnchorName;
|
||||
std::string tmp = path + ".tmp";
|
||||
int fd = open(tmp.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600);
|
||||
if (fd < 0) {
|
||||
err = "cannot create " + tmp + ": " + strerror(errno);
|
||||
return false;
|
||||
}
|
||||
size_t off = 0;
|
||||
while (off < pem.size()) {
|
||||
ssize_t w = write(fd, pem.data() + off, pem.size() - off);
|
||||
if (w <= 0) {
|
||||
if (w < 0 && errno == EINTR)
|
||||
continue;
|
||||
err = "cannot write " + tmp + ": " + strerror(errno);
|
||||
close(fd);
|
||||
unlink(tmp.c_str());
|
||||
return false;
|
||||
}
|
||||
off += (size_t)w;
|
||||
}
|
||||
fsync(fd);
|
||||
close(fd);
|
||||
|
||||
// 原子替换 + 收紧权限(目录可能已由 LinuxConfig 以 0755 创建)
|
||||
if (rename(tmp.c_str(), path.c_str()) != 0) {
|
||||
err = "cannot replace " + path + ": " + strerror(errno);
|
||||
unlink(tmp.c_str());
|
||||
return false;
|
||||
}
|
||||
chmod(path.c_str(), 0600);
|
||||
|
||||
Mprintf("[TLS] trust anchor saved to %s\n", path.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
bool TlsTrustAnchorRemove(std::string& err)
|
||||
{
|
||||
std::vector<std::string> paths;
|
||||
std::string dir = ConfigDir();
|
||||
if (!dir.empty())
|
||||
paths.push_back(dir + "/" + kAnchorName);
|
||||
std::string exed = ExeDir();
|
||||
if (!exed.empty())
|
||||
paths.push_back(exed + "/" + kAnchorName);
|
||||
|
||||
bool removed = false;
|
||||
for (size_t i = 0; i < paths.size(); ++i) {
|
||||
if (unlink(paths[i].c_str()) == 0) {
|
||||
removed = true;
|
||||
Mprintf("[TLS] trust anchor removed: %s\n", paths[i].c_str());
|
||||
} else if (errno != ENOENT) {
|
||||
err = "cannot remove " + paths[i] + ": " + strerror(errno);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (!removed) {
|
||||
err = "no trust anchor configured";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---- TlsChannel ----
|
||||
|
||||
void TlsChannel::CloseHandles()
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
|
||||
if (m_ssl) {
|
||||
SSL_free(m_ssl); // 不发送 close_notify:与 Windows 的 DeleteSecurityContext 同语义
|
||||
m_ssl = nullptr;
|
||||
}
|
||||
m_fd = -1;
|
||||
m_ready = false;
|
||||
}
|
||||
|
||||
bool TlsChannel::Handshake(int sock)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
|
||||
CloseHandles(); // 重连时清理上一次会话(recursive 锁,此处可重入)
|
||||
|
||||
// 在状态锁内取一份上下文:SSL_new 会递增 SSL_CTX 引用计数,此后即使 TlsReload()
|
||||
// 把全局上下文换掉(旧 ctx 被 SSL_CTX_free),本次握手的 SSL 仍然安全。
|
||||
SSL* ssl = nullptr;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_stateMtx);
|
||||
EnsureInitLocked();
|
||||
if (g_tlsCtx)
|
||||
ssl = SSL_new(g_tlsCtx);
|
||||
}
|
||||
if (!ssl) {
|
||||
Mprintf("[TLS] handshake called but no TLS context is available\n");
|
||||
return false;
|
||||
}
|
||||
if (SSL_set_fd(ssl, sock) != 1) {
|
||||
Mprintf("[TLS] SSL_set_fd failed\n");
|
||||
SSL_free(ssl);
|
||||
return false;
|
||||
}
|
||||
SSL_set_connect_state(ssl);
|
||||
|
||||
// 阻塞 socket:WANT_READ / WANT_WRITE 只在记录分片等极端情形出现,重试即可。
|
||||
for (;;) {
|
||||
ERR_clear_error();
|
||||
int r = SSL_do_handshake(ssl);
|
||||
if (r == 1)
|
||||
break;
|
||||
int e = SSL_get_error(ssl, r);
|
||||
if (e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE)
|
||||
continue;
|
||||
|
||||
if (e == SSL_ERROR_SSL) {
|
||||
unsigned long err = ERR_peek_last_error();
|
||||
char ebuf[256] = {0};
|
||||
if (err)
|
||||
ERR_error_string_n(err, ebuf, sizeof(ebuf));
|
||||
Mprintf("[TLS] handshake failed: %s\n", ebuf[0] ? ebuf : "SSL error");
|
||||
} else if (e == SSL_ERROR_SYSCALL) {
|
||||
Mprintf("[TLS] handshake failed: syscall error (%s)\n", strerror(errno));
|
||||
} else {
|
||||
Mprintf("[TLS] handshake failed: SSL_get_error=%d (peer closed?)\n", e);
|
||||
}
|
||||
SSL_free(ssl);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 单向 TLS:链必须钉扎到信任锚,且服务端确实出示了证书。默认 verify 只验链不校主机名,
|
||||
// 与 Windows 版(CertGetCertificateChain 只验链)行为一致。
|
||||
long vr = SSL_get_verify_result(ssl);
|
||||
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
|
||||
X509* peer = SSL_get1_peer_certificate(ssl);
|
||||
#else
|
||||
X509* peer = SSL_get_peer_certificate(ssl);
|
||||
#endif
|
||||
if (!peer || vr != X509_V_OK) {
|
||||
Mprintf("[TLS] server certificate not trusted against trust anchor (%s)\n",
|
||||
X509_verify_cert_error_string(vr));
|
||||
if (peer)
|
||||
X509_free(peer);
|
||||
SSL_free(ssl);
|
||||
return false;
|
||||
}
|
||||
X509_free(peer);
|
||||
|
||||
m_ssl = ssl;
|
||||
m_fd = sock;
|
||||
m_ready = true;
|
||||
Mprintf("[TLS] handshake OK (%s, server cert trusted)\n", SSL_get_version(ssl));
|
||||
return true;
|
||||
}
|
||||
|
||||
int TlsChannel::Recv(int sock, char* out, int outLen)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
|
||||
if (!m_ready || outLen <= 0) {
|
||||
Mprintf("[TLS] Recv called but m_ready=%d (outLen=%d), returning SOCKET_ERROR\n",
|
||||
(int)m_ready, outLen);
|
||||
return SOCKET_ERROR;
|
||||
}
|
||||
(void)sock; // SSL 已绑定 fd
|
||||
|
||||
for (;;) {
|
||||
ERR_clear_error();
|
||||
int n = SSL_read(m_ssl, out, outLen);
|
||||
if (n > 0)
|
||||
return n;
|
||||
int e = SSL_get_error(m_ssl, n);
|
||||
if (e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE)
|
||||
continue;
|
||||
if (e == SSL_ERROR_ZERO_RETURN)
|
||||
return 0; // close_notify:对端正常关闭
|
||||
if (e == SSL_ERROR_SYSCALL && ERR_peek_last_error() == 0)
|
||||
return 0; // 对端未发 close_notify 就断开(unexpected EOF),按关闭处理
|
||||
|
||||
Mprintf("[TLS] SSL_read failed: SSL_get_error=%d (%s)\n", e, strerror(errno));
|
||||
return SOCKET_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
int TlsChannel::Send(int sock, const char* data, int len)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
|
||||
if (!m_ready)
|
||||
return SOCKET_ERROR;
|
||||
if (len <= 0)
|
||||
return 0;
|
||||
(void)sock; // SSL 已绑定 fd
|
||||
|
||||
int total = 0;
|
||||
while (total < len) {
|
||||
ERR_clear_error();
|
||||
int n = SSL_write(m_ssl, data + total, len - total);
|
||||
if (n > 0) {
|
||||
total += n;
|
||||
continue;
|
||||
}
|
||||
int e = SSL_get_error(m_ssl, n);
|
||||
if (e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE)
|
||||
continue;
|
||||
|
||||
Mprintf("[TLS] SSL_write failed: SSL_get_error=%d (%s), sent=%d/%d\n",
|
||||
e, strerror(errno), total, len);
|
||||
return total > 0 ? total : SOCKET_ERROR;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
bool TlsChannel::HasPending() const
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
|
||||
if (!m_ready || !m_ssl)
|
||||
return false;
|
||||
// SSL_pending: 已解密未交付的明文;SSL_has_pending: 内部还缓冲着未处理的记录字节。
|
||||
// 任一为真都说明 select 看不到但可以立刻读,必须优先消费。
|
||||
return SSL_pending(m_ssl) > 0 || SSL_has_pending(m_ssl) == 1;
|
||||
}
|
||||
|
||||
#endif // __linux__ && !__ANDROID__
|
||||
+4
-26
@@ -36,6 +36,7 @@
|
||||
|
||||
// FileTransferV2 is in the same directory (common/)
|
||||
#include "FileTransferV2.h"
|
||||
#include "UnixPath.h"
|
||||
|
||||
// External declaration of clientID (defined in main.cpp/main.mm)
|
||||
extern uint64_t g_myClientID;
|
||||
@@ -186,34 +187,11 @@ private:
|
||||
// /:\ -> /
|
||||
// /: -> /
|
||||
// C:\Users\file.txt -> /Users/file.txt
|
||||
// %USERPROFILE%\Desktop\ -> /home/user/Desktop/ (or the XDG desktop folder)
|
||||
static std::string winPathToLinux(const char* winPath)
|
||||
{
|
||||
if (!winPath || !*winPath) return "/";
|
||||
|
||||
std::string p(winPath);
|
||||
// 1. Backslash -> forward slash
|
||||
for (auto& c : p) {
|
||||
if (c == '\\') c = '/';
|
||||
}
|
||||
// 2. Remove "X:/" or "X:" prefix (handles both /: and C: style)
|
||||
if (p.size() >= 3 && p[1] == ':' && p[2] == '/') {
|
||||
p = p.substr(3);
|
||||
} else if (p.size() >= 2 && p[1] == ':') {
|
||||
p = p.substr(2);
|
||||
}
|
||||
// 3. Ensure starts with /
|
||||
if (p.empty() || p[0] != '/') {
|
||||
p = "/" + p;
|
||||
}
|
||||
// 4. Merge consecutive slashes
|
||||
std::string result;
|
||||
result.reserve(p.size());
|
||||
for (size_t i = 0; i < p.size(); i++) {
|
||||
if (i > 0 && p[i] == '/' && p[i - 1] == '/')
|
||||
continue;
|
||||
result += p[i];
|
||||
}
|
||||
return result.empty() ? "/" : result;
|
||||
// 展开 %USERPROFILE% 等变量并把路径风格转成 Unix(见 UnixPath.h)
|
||||
return UnixPath::ToUnixPath(winPath ? winPath : "");
|
||||
}
|
||||
|
||||
// ---- Linux path -> Windows path (for sending to server) ----
|
||||
|
||||
+9
-31
@@ -18,6 +18,7 @@
|
||||
|
||||
#include "commands.h"
|
||||
#include "file_upload.h"
|
||||
#include "UnixPath.h"
|
||||
#include "../client/IOCPClient.h"
|
||||
#include <unistd.h>
|
||||
#include <sys/stat.h>
|
||||
@@ -230,20 +231,11 @@ public:
|
||||
}
|
||||
savePath += relPath;
|
||||
} else {
|
||||
// 服务端传输:使用相对路径
|
||||
// 将 Windows 路径转换为 Linux 路径
|
||||
savePath = fileName;
|
||||
for (char& c : savePath) {
|
||||
if (c == '\\') c = '/';
|
||||
}
|
||||
// 移除盘符前缀 (如 C:/)——只认「字母 + 冒号」,否则 /:data 这类合法路径会被改写
|
||||
if (savePath.size() >= 3 && isalpha((unsigned char)savePath[0]) && savePath[1] == ':' && savePath[2] == '/') {
|
||||
savePath = savePath.substr(2);
|
||||
}
|
||||
// 确保以 / 开头
|
||||
if (savePath.empty() || savePath[0] != '/') {
|
||||
savePath = "/" + savePath;
|
||||
}
|
||||
// 服务端传输:用服务端下发的绝对路径。
|
||||
// 快捷按钮(桌面/下载/用户主页)下发的目标目录是 %USERPROFILE%\...,
|
||||
// 由 WinPathToLinux 展开(见 UnixPath.h),与 Windows 上
|
||||
// ExpandEnvironmentStringsA 的效果一致。
|
||||
savePath = WinPathToLinux(fileName);
|
||||
}
|
||||
|
||||
// 目录处理
|
||||
@@ -438,25 +430,11 @@ public:
|
||||
closedir(d);
|
||||
}
|
||||
|
||||
// Windows 路径转 Linux 路径
|
||||
// Windows 路径转 Linux 路径。服务端对话框的快捷按钮(桌面/下载/用户主页)下发的是
|
||||
// %USERPROFILE%\Desktop\ 这类 Windows 变量路径,必须先展开(见 UnixPath.h)。
|
||||
static std::string WinPathToLinux(const std::string& winPath)
|
||||
{
|
||||
std::string p = winPath;
|
||||
// 1. 反斜杠 -> 正斜杠
|
||||
for (auto& c : p) {
|
||||
if (c == '\\') c = '/';
|
||||
}
|
||||
// 2. 移除 "X:/" 或 "X:" 前缀
|
||||
if (p.size() >= 3 && p[1] == ':' && p[2] == '/') {
|
||||
p = p.substr(3);
|
||||
} else if (p.size() >= 2 && p[1] == ':') {
|
||||
p = p.substr(2);
|
||||
}
|
||||
// 3. 确保以 / 开头
|
||||
if (p.empty() || p[0] != '/') {
|
||||
p = "/" + p;
|
||||
}
|
||||
return p;
|
||||
return UnixPath::ToUnixPath(winPath);
|
||||
}
|
||||
|
||||
// errno -> Win32 错误码:服务端 TOKEN_DOWNLOAD_ERROR 按 Win32 码分类
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
/**
|
||||
* UnixPath.h - Windows-style path handling on Unix clients
|
||||
*
|
||||
* The Windows server sends paths in its own dialect: drive letters ("C:\", or
|
||||
* "/:" for a Unix root), backslashes, and environment variables that the Windows
|
||||
* client expands with ExpandEnvironmentStringsA. The remote shortcut buttons
|
||||
* (server/2015Remote/FileManagerDlg.cpp: OnRemoteDesktop/OnRemoteDownloads/
|
||||
* OnRemoteHome) are the visible case — they send "%USERPROFILE%\Desktop\" and
|
||||
* friends, which a Unix client cannot open as-is.
|
||||
*
|
||||
* This header turns such paths into something the Unix clients can use:
|
||||
* %USERPROFILE% / %HOME% / %HOMEDRIVE%%HOMEPATH% -> $HOME
|
||||
* %USERNAME% / %USER% / %LOGNAME% -> login name
|
||||
* $HOME/Desktop (etc.) -> the XDG folder when
|
||||
* user-dirs.dirs maps it
|
||||
* (e.g. ~/桌面)
|
||||
* Unknown %VAR% tokens are left untouched, so paths that legitimately contain a
|
||||
* percent sign keep working as before.
|
||||
*
|
||||
* PLATFORM SUPPORT: Linux, macOS. Windows resolves these natively and does not
|
||||
* include this header.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <unistd.h>
|
||||
#include <pwd.h>
|
||||
#include <sys/stat.h>
|
||||
#include <cctype>
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <map>
|
||||
#include <string>
|
||||
|
||||
namespace UnixPath
|
||||
{
|
||||
|
||||
// ---- Home directory of the account the client runs as ----
|
||||
inline std::string HomeDir()
|
||||
{
|
||||
const char* home = getenv("HOME");
|
||||
if (home && *home) return home;
|
||||
struct passwd* pw = getpwuid(getuid());
|
||||
if (pw && pw->pw_dir && *pw->pw_dir) return pw->pw_dir;
|
||||
return "/";
|
||||
}
|
||||
|
||||
inline std::string TrimTrailingSlashes(std::string path)
|
||||
{
|
||||
while (path.size() > 1 && path.back() == '/') path.pop_back();
|
||||
return path;
|
||||
}
|
||||
|
||||
// Read ~/.config/user-dirs.dirs into {"Desktop" -> "/home/user/桌面", ...}.
|
||||
// The shortcuts use the English folder names, but on a localized desktop the
|
||||
// real folders are translated and only user-dirs.dirs knows where they are.
|
||||
// Entries pointing at a missing directory are dropped so the caller falls back
|
||||
// to the plain "$HOME/<Name>" path.
|
||||
inline std::map<std::string, std::string> LoadXdgUserDirs()
|
||||
{
|
||||
std::map<std::string, std::string> dirs;
|
||||
|
||||
std::string home = TrimTrailingSlashes(HomeDir());
|
||||
const char* cfgHome = getenv("XDG_CONFIG_HOME");
|
||||
std::string file = (cfgHome && *cfgHome) ? cfgHome : (home + "/.config");
|
||||
file += "/user-dirs.dirs";
|
||||
|
||||
std::ifstream in(file.c_str());
|
||||
std::string line;
|
||||
while (std::getline(in, line)) {
|
||||
size_t eq = line.find('=');
|
||||
if (eq == std::string::npos || line.compare(0, 4, "XDG_") != 0)
|
||||
continue;
|
||||
|
||||
std::string key = line.substr(4, eq - 4); // DESKTOP_DIR
|
||||
if (key.size() <= 4 || key.compare(key.size() - 4, 4, "_DIR") != 0)
|
||||
continue;
|
||||
|
||||
std::string value = line.substr(eq + 1);
|
||||
if (value.size() >= 2 && value.front() == '"' && value.back() == '"')
|
||||
value = value.substr(1, value.size() - 2);
|
||||
|
||||
// $HOME / ${HOME} are the only variables user-dirs.dirs may use
|
||||
for (size_t pos; (pos = value.find("${HOME}")) != std::string::npos; )
|
||||
value.replace(pos, 7, home);
|
||||
for (size_t pos; (pos = value.find("$HOME")) != std::string::npos; )
|
||||
value.replace(pos, 5, home);
|
||||
|
||||
// DESKTOP_DIR -> "Desktop"
|
||||
std::string name = key.substr(0, key.size() - 4);
|
||||
for (auto& c : name) c = (char)tolower((unsigned char)c);
|
||||
if (!name.empty()) name[0] = (char)toupper((unsigned char)name[0]);
|
||||
|
||||
if (!value.empty() && access(value.c_str(), F_OK) == 0)
|
||||
dirs[name] = TrimTrailingSlashes(value);
|
||||
}
|
||||
return dirs;
|
||||
}
|
||||
|
||||
inline const std::map<std::string, std::string>& XdgUserDirs()
|
||||
{
|
||||
// C++11 guarantees a thread-safe one-time initialization of the local static
|
||||
static const std::map<std::string, std::string> dirs = LoadXdgUserDirs();
|
||||
return dirs;
|
||||
}
|
||||
|
||||
// Rewrite $HOME/Desktop (etc.) to the localized folder user-dirs.dirs names.
|
||||
// Expects a slash-separated absolute path.
|
||||
inline std::string RemapXdgUserDir(const std::string& path)
|
||||
{
|
||||
std::string home = TrimTrailingSlashes(HomeDir());
|
||||
if (path.compare(0, home.size(), home) != 0)
|
||||
return path;
|
||||
|
||||
const std::map<std::string, std::string>& dirs = XdgUserDirs();
|
||||
if (dirs.empty())
|
||||
return path;
|
||||
|
||||
std::string base = (home == "/") ? "" : home;
|
||||
for (const auto& kv : dirs) {
|
||||
std::string prefix = base + "/" + kv.first;
|
||||
if (path == prefix ||
|
||||
(path.compare(0, prefix.size(), prefix) == 0 && path[prefix.size()] == '/'))
|
||||
return kv.second + path.substr(prefix.size());
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
// Expand %USERPROFILE% style variables in a path the server sent.
|
||||
inline std::string ExpandWindowsEnvVars(const std::string& in)
|
||||
{
|
||||
std::string out;
|
||||
out.reserve(in.size());
|
||||
|
||||
for (size_t i = 0; i < in.size(); ) {
|
||||
if (in[i] != '%') {
|
||||
out += in[i++];
|
||||
continue;
|
||||
}
|
||||
size_t end = in.find('%', i + 1);
|
||||
if (end == std::string::npos) {
|
||||
out.append(in, i, std::string::npos);
|
||||
break;
|
||||
}
|
||||
|
||||
// Windows variable names are case-insensitive
|
||||
std::string name = in.substr(i + 1, end - i - 1);
|
||||
for (auto& c : name) c = (char)toupper((unsigned char)c);
|
||||
|
||||
bool known = true;
|
||||
std::string value;
|
||||
if (name == "USERPROFILE" || name == "HOME" || name == "HOMEPATH") {
|
||||
value = HomeDir();
|
||||
} else if (name == "HOMEDRIVE") {
|
||||
// "%HOMEDRIVE%%HOMEPATH%" has to come out as a single absolute home path
|
||||
value = "";
|
||||
} else if (name == "USERNAME" || name == "USER" || name == "LOGNAME") {
|
||||
const char* user = getenv("USER");
|
||||
if (!user || !*user) user = getenv("LOGNAME");
|
||||
struct passwd* pw = getpwuid(getuid());
|
||||
value = (user && *user) ? user : ((pw && pw->pw_name) ? pw->pw_name : "");
|
||||
} else {
|
||||
known = false;
|
||||
}
|
||||
|
||||
if (known)
|
||||
out += value;
|
||||
else
|
||||
out.append(in, i, end - i + 1);
|
||||
|
||||
i = end + 1;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Convert a Windows-dialect path into one the Unix clients can open:
|
||||
// %USERPROFILE%\Desktop\ -> /home/user/Desktop/ (or the XDG desktop folder)
|
||||
// /:\home\user\file.txt -> /home/user/file.txt
|
||||
// C:\Users\file.txt -> /Users/file.txt
|
||||
// "" -> /
|
||||
inline std::string ToUnixPath(const std::string& winPath)
|
||||
{
|
||||
if (winPath.empty()) return "/";
|
||||
|
||||
std::string p = ExpandWindowsEnvVars(winPath);
|
||||
|
||||
// 1. Backslash -> forward slash
|
||||
for (auto& c : p) {
|
||||
if (c == '\\') c = '/';
|
||||
}
|
||||
// 2. Remove "X:/" or "X:" prefix (handles both /: and C: style)
|
||||
if (p.size() >= 3 && p[1] == ':' && p[2] == '/') {
|
||||
p = p.substr(3);
|
||||
} else if (p.size() >= 2 && p[1] == ':') {
|
||||
p = p.substr(2);
|
||||
}
|
||||
// 3. Ensure starts with /
|
||||
if (p.empty() || p[0] != '/') {
|
||||
p = "/" + p;
|
||||
}
|
||||
// 4. Merge consecutive slashes
|
||||
std::string result;
|
||||
result.reserve(p.size());
|
||||
for (size_t i = 0; i < p.size(); i++) {
|
||||
if (i > 0 && p[i] == '/' && p[i - 1] == '/')
|
||||
continue;
|
||||
result += p[i];
|
||||
}
|
||||
if (result.empty()) return "/";
|
||||
// 5. "$HOME/Desktop" -> localized folder (~/桌面 ...) when user-dirs.dirs says so
|
||||
return RemapXdgUserDir(result);
|
||||
}
|
||||
|
||||
} // namespace UnixPath
|
||||
@@ -1,8 +1,8 @@
|
||||
# 传输层单向 TLS 加密设计(按需加密)
|
||||
|
||||
> 版本:v0.5 · 状态:**Go 服务端 + Windows 客户端已实现并验证;信任锚改存注册表;MFC 主控端(阶段 3)未施工** · 日期:2026-10-14
|
||||
> 版本:v0.7 · 状态:**Go 服务端 + Windows/Linux 客户端已实现并验证;Linux 客户端支持下发即时热切换;MFC 主控端见 `TransportTLS_MFCServer_Design.md`;macOS/Android 未接入** · 日期:2026-10-28(Linux 客户端接入 + 热切换)
|
||||
> 目标:让 YAMA 设备端口(TCP 6543)在继续兼容老客户端(明文/XOR)的同时,允许新客户端在拿到证书后按需开启**单向 TLS** 加密传输。
|
||||
> 本期范围:**Go 服务端(`server/go`)+ Windows 客户端**;MFC 服务端(`server/2015Remote`)延后。
|
||||
> 本期范围:**Go 服务端(`server/go`)+ Windows 客户端 + Linux 客户端**。
|
||||
>
|
||||
> 需求原文(三点,逐一对应下文):
|
||||
> 1. 新客户端**默认不加密**,行为与老客户端完全一致;
|
||||
@@ -23,8 +23,8 @@
|
||||
- 不做 **mTLS / 客户端证书**:单向 TLS 不验证客户端证书,客户端身份仍由隧道内的现有登录(`PwdHmac` V1 / `ECDSA` V2)承担。
|
||||
- 不做传输层 PSK(`YAMA_TRANSPORT_KEY`)方案——本设计改用证书,更贴合「颁发证书」的运维模型。
|
||||
- 不改应用层协议(flag 帧格式 / XOR / zstd),不做「TLS 内去掉 XOR」的二次精简(后续可选)。
|
||||
- 不做加密开关的运行时热切换(证书只在客户端启动时读取一次,改配置需重启——这正是需求)。
|
||||
- 不做 Linux / macOS / Android 客户端的 TLS 接入(本文以 Windows MFC 客户端为主,其余平台同样式跟进)。
|
||||
- Windows 客户端**不做**加密开关的运行时热切换(证书只在进程启动时读取一次,改配置需重启——这正是需求)。Linux 客户端例外:服务端下发 166/167 后立即重载信任锚并重连切换(§6.6),语义差异见该节。
|
||||
- macOS / Android 客户端的 TLS 接入不在本期(Linux 客户端已按同一模式接入,见 §6.6)。
|
||||
- 不做 **MFC 服务端(`server/2015Remote`)的 TLS 接入**——本期只做 Go 服务端(`server/go`),MFC 主控端延后到阶段 3。
|
||||
|
||||
## 2. 现状与复用
|
||||
@@ -190,6 +190,8 @@ func (s *Server) wrapTLS(conn net.Conn) net.Conn {
|
||||
|
||||
启动时(连接前)按优先级找信任锚:① 注册表 `Software\<exehash>\settings\tls_cert`(REG_SZ 存 PEM 正文)→ ② `settings.ini` `[settings] tls_cert` 路径 → ③ exe 同目录 `yama-ca.pem`。找到即走 TLS,否则明文。实现:`client/TlsChannel.cpp` 的 `ReadTrustAnchor()` + `TlsEnabled()`(`std::call_once` 惰性加载、线程安全、幂等)。
|
||||
|
||||
Linux 无注册表,信任锚按:① `$XDG_CONFIG_HOME/ghost/yama-ca.pem`(默认 `~/.config/ghost/yama-ca.pem`)→ ② 程序同目录 `yama-ca.pem`。文件**存在即视为已配置**:读取/解析失败一律拒绝连接(fail-closed)。实现:`client/TlsChannelLinux.cpp`。
|
||||
|
||||
### 6.2 TLS 栈选型(已定:Schannel)
|
||||
|
||||
- **已选 Schannel(Windows 原生 SSPI)**:零第三方依赖/零额外 DLL 部署,`secur32.lib`/`crypt32.lib` 均为系统库(`secur32.lib` 已在 `CFFmpegH264Encoder.cpp:38` 链接)。
|
||||
@@ -223,6 +225,22 @@ Schannel 流模式(`ISC_REQ_STREAM`)下,`DecryptMessage` 会把输入的
|
||||
`STREAM_HEADER/DATA/TRAILER` 三段布局,本就正确。这一处是联调阶段实际踩到的、唯一的方向性
|
||||
不对称 bug,已修复。
|
||||
|
||||
### 6.6 Linux 客户端实现(OpenSSL,2026-10-28)
|
||||
|
||||
- **选型**:OpenSSL(`libssl`)。Linux 构建早已因 `libsign.a` 链接 `libcrypto`,只多链一个 `OpenSSL::SSL`,不引入新的运行时依赖包(同一 OpenSSL 3 包提供 `libcrypto.so.3` / `libssl.so.3`)。
|
||||
- **代码组织**:`client/TlsChannel.h` 按平台分派(`_WIN32` → Schannel,`__linux__ && !__ANDROID__` → OpenSSL),Windows 分支内容不变;实现文件为 `client/TlsChannelLinux.cpp`。`YAMA_TLS_CHANNEL` 宏标注「本平台有 TLS 通道」,`IOCPClient` 用它替代原先的 `#ifdef _WIN32`,因此主连接与子连接共用同一接线点。macOS/Android 不定义该宏,维持明文。
|
||||
- **语义对齐**:`TLS 1.2` 钉扎(min=max,与 `SP_PROT_TLS1_2_CLIENT` 及两套服务端一致);单向 TLS、不提供客户端证书、不校主机名、不做吊销检查;`SSL_VERIFY_PEER` + 只含信任锚的 `X509_STORE`(不含系统根库,严格钉扎),握手内完成链校验,失败即断开(fail-closed)。
|
||||
- **缓冲差异**:OpenSSL 自己管理记录缓冲,不需要 Schannel 的 `m_raw`/`m_pending`;一次 `SSL_read` 交付不完的明文留在 `SSL` 内部,接收线程在 `select` 前用 `SSL_pending() || SSL_has_pending()` 优先消费,否则剩余字节会被 2 秒 `select` 超时卡住。
|
||||
- **下发/撤销**:`COMMAND_TLS_ENABLE`(166) 的 PEM 正文写入 `~/.config/ghost/yama-ca.pem`(目录 0700、文件 0600、临时文件 + rename 原子替换);`COMMAND_TLS_DISABLE`(167) 删除该文件(含程序目录同名回退文件)。写入前先用 OpenSSL 解析一遍,不是合法证书就整包拒绝并保留原状态。
|
||||
- **热切换(与 Windows 的唯一语义差异)**:落盘后立即 `TlsReload()` 重建 `SSL_CTX` 并更新开关,然后断开主连接、由外层重连循环用新传输方式重连——**主控端菜单点下去几秒内就生效**,不需要重启客户端(Windows 客户端仍需重启进程)。
|
||||
- 状态不再是 `std::call_once`,而是 `g_stateMtx` 保护的 `{g_tlsEnabled, g_tlsError, g_tlsCtx}`;`TlsEnabled()/TlsLoadError()/TlsReload()/Handshake()` 都在这把锁下读写。
|
||||
- **已建立的连接不受影响**:`SSL_new` 会递增 `SSL_CTX` 引用计数,`TlsReload` 释放旧 ctx 后旧的 `SSL` 仍然安全(已用「连接保持打开时撤销锚」验证)。
|
||||
- **只在传输方式真的变了(明文↔TLS)时才重连**;仅换锚(例如证书轮换,仍是 TLS)不打断现有会话,新锚从下一条新连接生效。
|
||||
- 热重载遇到坏锚时**保留原状态**并记日志,不把正在工作的客户端打死(下次启动仍按 fail-closed 语义)。
|
||||
- 重连由 `DataProcess`(接收线程)只置 `g_needReconnect` 标志,由主心跳线程 `Disconnect()` 后走外层重连循环——避免在接收线程里关 socket 与主线程发送竞争。
|
||||
- **代价**:此刻若正处于远程桌面/文件传输会话,主连接重建会中断该会话(子连接随之失效)。这是「立即生效」的固有代价。
|
||||
- **上报**:登录 `szReserved[19]`(`RES_TLS`)填 `TlsEnabled() ? 1 : 0`,主控端主机信息显示 Y/N。热切换后重连会重新登录,登录前用 `RefreshLoginTls()` 刷新该字段,主控端在线列表的 TLS 列随之翻转。
|
||||
|
||||
## 7. 兼容矩阵
|
||||
|
||||
| 客户端 | 服务端行为 | 结果 |
|
||||
@@ -286,7 +304,9 @@ Set-ItemProperty -Path 'HKCU:\Software\<exehash>\settings' -Name 'tls_cert' -Val
|
||||
|
||||
兼容旧方式:把信任锚复制到客户端目录并命名为 `yama-ca.pem`(或经 `settings.ini` `[settings] tls_cert` 指向),重启客户端。
|
||||
|
||||
移除注册表值(或删除文件)并重启即退回明文。**远程下发/撤销信任锚属后续工作,本期仅支持本地写注册表。**
|
||||
Linux 客户端:把信任锚放到 `~/.config/ghost/yama-ca.pem`(或程序同目录 `yama-ca.pem`),重启客户端生效。MFC 主控端的「启用/停用 TLS 传输」指令对选中主机下发时也会写/删该文件,**且 Linux 客户端会立即热切换并重连**(无需重启,见 §6.6);Windows 客户端仍需重启。
|
||||
|
||||
移除注册表值(或删除文件)并重启即退回明文。远程下发/撤销:Windows 经 `COMMAND_TLS_ENABLE/DISABLE` 写注册表(重启生效),Linux 写/删上述配置文件(立即生效)。
|
||||
|
||||
## 10. 测试计划
|
||||
|
||||
@@ -302,6 +322,7 @@ Set-ItemProperty -Path 'HKCU:\Software\<exehash>\settings' -Name 'tls_cert' -Val
|
||||
|
||||
- **阶段 1(Go 服务端,本期优先)**:`Config` + `tls.Config` + `acceptLoop` 检测回放;明文路径零改动。可独立上线、独立验证——用 `openssl s_client` 或 Go 测试客户端即可联调 TLS 链路,无需真实客户端配合。
|
||||
- **阶段 2(Windows 客户端)**:证书检测 + TLS 栈 + fail-closed。
|
||||
- **阶段 2b(Linux 客户端)**:OpenSSL 实现,复用同一接线点与协议语义(2026-10-28 完成)。
|
||||
- **阶段 3(MFC 服务端 `server/2015Remote`,延后)**:与 Go 服务端同款的 TLS 检测 + 解包接入。设计稿见 `docs/TransportTLS_MFCServer_Design.md`。
|
||||
- **回滚**:服务端清空 `YAMA_TLS_CERT/KEY` 即回到纯明文;客户端删除注册表 `tls_cert` 值(或 `yama-ca.pem` 文件)即回明文。
|
||||
|
||||
@@ -310,4 +331,4 @@ Set-ItemProperty -Path 'HKCU:\Software\<exehash>\settings' -Name 'tls_cert' -Val
|
||||
1. ~~客户端 TLS 栈最终选型~~ → **已定 Schannel**(见 §6.2,2026-10-13 落地)。
|
||||
2. ~~信任锚文件固定名(`yama-ca.pem`)是否需可配置~~ → **已改为注册表 `tls_cert` 值优先、文件回退**(见 §6.1/§9.3,2026-10-14)。
|
||||
3. 是否同步把「TLS 内去掉 XOR」列为后续精简项(当前保留 XOR,换取零协议改动)。
|
||||
4. Linux / macOS / Android 客户端的 TLS 接入排期。
|
||||
4. ~~Linux / macOS / Android 客户端的 TLS 接入排期~~ → **Linux 已接入(OpenSSL,2026-10-28)**;macOS / Android 待定(macOS 需 Security.framework 或自带 OpenSSL,Android 需在 NDK 内构建 OpenSSL)。
|
||||
@@ -28,6 +28,7 @@ set(SOURCES
|
||||
main.cpp
|
||||
../client/Buffer.cpp
|
||||
../client/IOCPClient.cpp
|
||||
../client/TlsChannelLinux.cpp # Linux 客户端单向 TLS(OpenSSL),见 client/TlsChannel.h
|
||||
../client/sign_shim_unix.cpp
|
||||
)
|
||||
add_executable(ghost ${SOURCES})
|
||||
@@ -45,9 +46,10 @@ target_link_libraries(ghost PRIVATE "${CMAKE_SOURCE_DIR}/lib/libzstd.a")
|
||||
# 该库由 SimplePlugins 仓库本地构建后放置于 lib/,构建机需先准备好
|
||||
target_link_libraries(ghost PRIVATE "${CMAKE_SOURCE_DIR}/lib/libsign.a")
|
||||
|
||||
# libsign.a 内部使用 OpenSSL HMAC,需要在最终可执行链接 libcrypto
|
||||
# libsign.a 内部使用 OpenSSL HMAC,需要在最终可执行链接 libcrypto;
|
||||
# 客户端传输层 TLS(client/TlsChannelLinux.cpp)另需 libssl。
|
||||
find_package(OpenSSL REQUIRED)
|
||||
target_link_libraries(ghost PRIVATE OpenSSL::Crypto)
|
||||
target_link_libraries(ghost PRIVATE OpenSSL::Crypto OpenSSL::SSL)
|
||||
|
||||
# 链接 dl 库(dlopen/dlsym 用于运行时加载 X11)
|
||||
target_link_libraries(ghost PRIVATE dl)
|
||||
|
||||
@@ -51,6 +51,10 @@ CONNECT_ADDRESS g_SETTINGS = { FLAG_GHOST, "91.99.165.207", "443", CLIENT_TYPE_L
|
||||
// 全局状态
|
||||
State g_bExit = S_CLIENT_NORMAL;
|
||||
static std::atomic<bool> g_needResendLogin(false); // 分组变更后需要重发登录信息
|
||||
// 传输层热切换(服务端 COMMAND_TLS_ENABLE/DISABLE 改了信任锚)后需要重建连接。
|
||||
// DataProcess 跑在接收线程上,直接关 socket 会和主线程的发送竞争,所以只置标志,
|
||||
// 由主心跳循环择机 Disconnect 并重连。
|
||||
static std::atomic<bool> g_needReconnect(false);
|
||||
|
||||
// 自升级(COMMAND_UPDATE):fork+execv 重启自己时需要原始命令行,
|
||||
// 失败回报需要主连接(DataProcess 的 user 参数为 NULL,只能靠全局)。
|
||||
@@ -378,6 +382,28 @@ void* FileManagerThread(void* /*param*/)
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// 信任锚已落盘/已删除:热重载 TLS 状态,必要时请求主循环重建连接。
|
||||
// 只在传输方式真正变化(明文↔TLS)时重连;仅换证书(仍是 TLS)不打断现有会话,
|
||||
// 新锚从下一条新连接开始生效。
|
||||
static void ApplyTlsAnchorChange(void* user)
|
||||
{
|
||||
bool before = TlsEnabled();
|
||||
std::string err;
|
||||
if (!TlsReload(err)) {
|
||||
Mprintf("** [%p] TLS reload failed: %s (keeping current transport) ***\n", user, err.c_str());
|
||||
return;
|
||||
}
|
||||
bool after = TlsEnabled();
|
||||
if (before == after) {
|
||||
Mprintf("** [%p] TLS trust anchor updated, transport unchanged (%s) ***\n",
|
||||
user, after ? "TLS" : "plaintext");
|
||||
return;
|
||||
}
|
||||
g_needReconnect.store(true);
|
||||
Mprintf("** [%p] TLS transport switched to %s, reconnecting ***\n",
|
||||
user, after ? "TLS" : "plaintext");
|
||||
}
|
||||
|
||||
int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
||||
{
|
||||
if (szBuffer == nullptr || ulLength == 0)
|
||||
@@ -481,6 +507,32 @@ 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_TLS_ENABLE) {
|
||||
// 服务端下发信任锚证书(载荷与 Windows 一致:szBuffer+1 起为 PEM 正文)。
|
||||
// Windows 写注册表 settings\tls_cert;Linux 写 ~/.config/ghost/yama-ca.pem。
|
||||
// 与 Windows 不同:Linux 落盘后热重载并重连,立即切换(Windows 仍需重启进程)。
|
||||
if (ulLength > 1) {
|
||||
std::string pem((char*)szBuffer + 1, ulLength - 1);
|
||||
std::string err;
|
||||
if (TlsTrustAnchorSave(pem, err)) {
|
||||
Mprintf("** [%p] TLS trust anchor received and saved ***\n", user);
|
||||
ApplyTlsAnchorChange(user);
|
||||
} else {
|
||||
Mprintf("** [%p] TLS trust anchor save failed: %s ***\n", user, err.c_str());
|
||||
}
|
||||
} else {
|
||||
// 没有证书正文就等于「启用但没有锚」——不该悄悄忽略,留一行便于排查。
|
||||
Mprintf("** [%p] COMMAND_TLS_ENABLE without a certificate payload, ignored\n", user);
|
||||
}
|
||||
} else if (szBuffer[0] == COMMAND_TLS_DISABLE) {
|
||||
// 撤销信任锚:删除配置文件并热重载,当前连接若是 TLS 就重连回明文。
|
||||
std::string err;
|
||||
if (TlsTrustAnchorRemove(err)) {
|
||||
Mprintf("** [%p] TLS trust anchor removed ***\n", user);
|
||||
ApplyTlsAnchorChange(user);
|
||||
} else {
|
||||
Mprintf("** [%p] TLS trust anchor removal: %s ***\n", user, err.c_str());
|
||||
}
|
||||
} else if (szBuffer[0] == COMMAND_UPDATE) {
|
||||
// 服务端"升级程序"菜单下发新版本 ELF
|
||||
Mprintf("** [%p] Received 'UPDATE' command (%u bytes) ***\n", user, (unsigned)ulLength);
|
||||
@@ -1032,6 +1084,37 @@ static void ApplySelfUpdate(const PBYTE szBuffer, ULONG ulLength)
|
||||
g_bExit = S_CLIENT_UPDATE;
|
||||
}
|
||||
|
||||
// 登录信息 szReserved 里的 [19] RES_TLS 是「当前」传输状态的快照,服务端在线列表的
|
||||
// TLS 列就取这个值。热切换后重连会重新登录,必须在这里刷新,否则列里会一直显示旧值。
|
||||
// 只在主线程调用(与 SendLoginInfo 同一线程),避免和接收线程抢同一个结构体。
|
||||
static void RefreshLoginTls(LOGIN_INFOR& info)
|
||||
{
|
||||
std::vector<std::string> fields;
|
||||
std::string s(info.szReserved);
|
||||
size_t pos = 0;
|
||||
for (;;) {
|
||||
size_t bar = s.find('|', pos);
|
||||
if (bar == std::string::npos) {
|
||||
fields.push_back(s.substr(pos));
|
||||
break;
|
||||
}
|
||||
fields.push_back(s.substr(pos, bar - pos));
|
||||
pos = bar + 1;
|
||||
}
|
||||
while (fields.size() <= (size_t)RES_TLS)
|
||||
fields.push_back("");
|
||||
fields[RES_TLS] = TlsEnabled() ? "1" : "0";
|
||||
|
||||
std::string joined;
|
||||
for (size_t i = 0; i < fields.size(); ++i) {
|
||||
if (i)
|
||||
joined += '|';
|
||||
joined += fields[i];
|
||||
}
|
||||
strncpy(info.szReserved, joined.c_str(), sizeof(info.szReserved) - 1);
|
||||
info.szReserved[sizeof(info.szReserved) - 1] = '\0';
|
||||
}
|
||||
|
||||
// 用法: ./ghost [-d] [IP] [端口]
|
||||
// -d 后台守护进程模式
|
||||
// 示例: ./ghost -d 192.168.1.100 6543
|
||||
@@ -1191,6 +1274,7 @@ int main(int argc, char* argv[])
|
||||
logInfo.AddReserved(std::to_string(g_myClientID).c_str()); // [16] RES_CLIENT_ID
|
||||
logInfo.AddReserved((int)getpid()); // [17] RES_PID
|
||||
logInfo.AddReserved(getFileSize(exePath).c_str()); // [18] RES_FILESIZE
|
||||
logInfo.AddReserved(TlsEnabled() ? 1 : 0); // [19] RES_TLS(有信任锚即 1)
|
||||
|
||||
// 服务端签名输入:与服务端 AddList 处签名格式一致(startTime + "|" + clientID)
|
||||
ClientAuth::g_loginMsg = std::string(logInfo.szStartTime) + "|" + std::to_string(g_myClientID);
|
||||
@@ -1210,6 +1294,8 @@ int main(int argc, char* argv[])
|
||||
|
||||
// 进入新连接,重置服务端身份校验状态
|
||||
ClientAuth::OnNewConnection();
|
||||
// 传输方式可能已被热切换(TLS 启/停),登录上报的 RES_TLS 必须反映本次连接。
|
||||
RefreshLoginTls(logInfo);
|
||||
ClientObject->SendLoginInfo(logInfo.Speed(clock() - c));
|
||||
|
||||
// 新连接:把 ACK 看门狗喂到当前时间,避免循环刚进来就被误判为超时
|
||||
@@ -1228,6 +1314,7 @@ int main(int argc, char* argv[])
|
||||
strncpy(logInfo.szPCName, hostname, sizeof(logInfo.szPCName) - 1);
|
||||
}
|
||||
logInfo.szPCName[sizeof(logInfo.szPCName) - 1] = '\0';
|
||||
RefreshLoginTls(logInfo);
|
||||
ClientObject->SendLoginInfo(logInfo);
|
||||
Mprintf(">> Resent login info after group change\n");
|
||||
}
|
||||
@@ -1235,10 +1322,18 @@ int main(int argc, char* argv[])
|
||||
// 等待心跳间隔(每秒检查一次退出条件,保证及时响应)
|
||||
int interval = g_heartbeatInterval > 0 ? g_heartbeatInterval : 30;
|
||||
for (int i = 0; i < interval; ++i) {
|
||||
if (g_needReconnect.load(std::memory_order_relaxed))
|
||||
break;
|
||||
if (!ClientObject->IsRunning() || !ClientObject->IsConnected() || g_bExit != S_CLIENT_NORMAL)
|
||||
break;
|
||||
Sleep(1000);
|
||||
}
|
||||
// 信任锚热切换(COMMAND_TLS_ENABLE/DISABLE):断开后由外层循环用新传输方式重连。
|
||||
if (g_needReconnect.exchange(false)) {
|
||||
Mprintf(">>> Reconnecting to apply the TLS transport change\n");
|
||||
ClientObject->Disconnect();
|
||||
break;
|
||||
}
|
||||
if (!ClientObject->IsRunning() || !ClientObject->IsConnected() || g_bExit != S_CLIENT_NORMAL)
|
||||
break;
|
||||
|
||||
|
||||
@@ -4793,8 +4793,11 @@ void CMy2015RemoteDlg::OnExperimentTlsEnable()
|
||||
_T("提示"), MB_ICONWARNING);
|
||||
return;
|
||||
}
|
||||
// 二次确认:避免误点就切换被控端 TLS;客户端写注册表,下次启动生效
|
||||
if (IDYES != MessageBoxL(_T("确定对选中主机启用 TLS 传输吗?(客户端下次启动生效)"),
|
||||
// 二次确认:避免误点就切换被控端 TLS。
|
||||
// 生效时机因客户端而异:Windows 写注册表、下次启动生效;Linux 落盘后立即热切换并
|
||||
// 断开重连(见 client/TlsChannelLinux.cpp 的 TlsReload),正在进行的远程会话会中断。
|
||||
if (IDYES != MessageBoxL(_T("确定对选中主机启用 TLS 传输吗?\n"
|
||||
"(Linux 客户端立即生效并断线重连;Windows 客户端下次启动生效)"),
|
||||
_T("提示"), MB_ICONQUESTION | MB_YESNO)) return;
|
||||
|
||||
// 读取服务端证书(信任锚),随启用指令一并下发;客户端写入注册表 settings\tls_cert。
|
||||
@@ -4826,7 +4829,8 @@ void CMy2015RemoteDlg::OnExperimentTlsDisable()
|
||||
_T("提示"), MB_ICONWARNING);
|
||||
return;
|
||||
}
|
||||
if (IDYES != MessageBoxL(_T("确定取消选中主机的 TLS 传输吗?(客户端下次启动生效)"),
|
||||
if (IDYES != MessageBoxL(_T("确定取消选中主机的 TLS 传输吗?\n"
|
||||
"(Linux 客户端立即生效并断线重连;Windows 客户端下次启动生效)"),
|
||||
_T("提示"), MB_ICONQUESTION | MB_YESNO)) return;
|
||||
BYTE bToken = COMMAND_TLS_DISABLE; //向被控端发送停用 TLS 传输命令
|
||||
SendSelectedCommand(&bToken, sizeof(BYTE));
|
||||
|
||||
@@ -2092,8 +2092,8 @@ TLS
|
||||
证书/私钥加载失败,加密功能未生效。请检查文件路径与格式(证书 PEM、私钥 PKCS#8)。=Zertifikat/privater Schluessel konnte nicht geladen werden; Verschluesselung ist inaktiv. Bitte Pfad und Format pruefen (PEM-Zertifikat, PKCS#8-Schluessel).
|
||||
TLS传输=TLS-Transport
|
||||
取消TLS=TLS deaktivieren
|
||||
确定对选中主机启用 TLS 传输吗?(客户端下次启动生效)=TLS-Transport fuer die ausgewaehlten Hosts aktivieren? (wirkt nach Client-Neustart)
|
||||
确定取消选中主机的 TLS 传输吗?(客户端下次启动生效)=TLS-Transport fuer die ausgewaehlten Hosts deaktivieren? (wirkt nach Client-Neustart)
|
||||
确定对选中主机启用 TLS 传输吗?\n(Linux 客户端立即生效并断线重连;Windows 客户端下次启动生效)=TLS-Transport fuer die ausgewaehlten Hosts aktivieren?\n(Linux-Clients wechseln sofort und verbinden sich neu; Windows-Clients erst nach dem Neustart)
|
||||
确定取消选中主机的 TLS 传输吗?\n(Linux 客户端立即生效并断线重连;Windows 客户端下次启动生效)=TLS-Transport fuer die ausgewaehlten Hosts deaktivieren?\n(Linux-Clients wechseln sofort und verbinden sich neu; Windows-Clients erst nach dem Neustart)
|
||||
服务端未启用 TLS 证书,无法切换客户端 TLS 传输=Server-TLS-Zertifikat ist nicht aktiviert; TLS-Transport der Clients kann nicht umgeschaltet werden
|
||||
读取服务端 TLS 证书失败,无法下发=Server-TLS-Zertifikat konnte nicht gelesen werden; Verteilung nicht moeglich
|
||||
白名单=Whitelist
|
||||
|
||||
@@ -2111,8 +2111,8 @@ TLS
|
||||
证书/私钥加载失败,加密功能未生效。请检查文件路径与格式(证书 PEM、私钥 PKCS#8)。=Failed to load certificate/private key; encryption is not active. Check the file path and format (PEM certificate, PKCS#8 private key).
|
||||
TLS传输=TLS Transport
|
||||
取消TLS=Disable TLS
|
||||
确定对选中主机启用 TLS 传输吗?(客户端下次启动生效)=Enable TLS transport for the selected host? (takes effect after the client restarts)
|
||||
确定取消选中主机的 TLS 传输吗?(客户端下次启动生效)=Disable TLS transport for the selected host? (takes effect after the client restarts)
|
||||
确定对选中主机启用 TLS 传输吗?\n(Linux 客户端立即生效并断线重连;Windows 客户端下次启动生效)=Enable TLS transport for the selected host?\n(Linux clients switch immediately and reconnect; Windows clients apply it on next start)
|
||||
确定取消选中主机的 TLS 传输吗?\n(Linux 客户端立即生效并断线重连;Windows 客户端下次启动生效)=Disable TLS transport for the selected host?\n(Linux clients switch immediately and reconnect; Windows clients apply it on next start)
|
||||
服务端未启用 TLS 证书,无法切换客户端 TLS 传输=Server TLS certificate is not enabled; cannot toggle client TLS transport
|
||||
读取服务端 TLS 证书失败,无法下发=Failed to read the server TLS certificate; cannot distribute
|
||||
白名单=Whitelist
|
||||
|
||||
@@ -2102,8 +2102,8 @@ TLS
|
||||
证书/私钥加载失败,加密功能未生效。请检查文件路径与格式(证书 PEM、私钥 PKCS#8)。=憑證/私鑰載入失敗,加密功能未生效。請檢查檔案路徑與格式(憑證 PEM、私鑰 PKCS#8)。
|
||||
TLS传输=TLS 傳輸
|
||||
取消TLS=停用 TLS
|
||||
确定对选中主机启用 TLS 传输吗?(客户端下次启动生效)=確定對選取主機啟用 TLS 傳輸嗎?(用戶端下次啟動生效)
|
||||
确定取消选中主机的 TLS 传输吗?(客户端下次启动生效)=確定取消選取主機的 TLS 傳輸嗎?(用戶端下次啟動生效)
|
||||
确定对选中主机启用 TLS 传输吗?\n(Linux 客户端立即生效并断线重连;Windows 客户端下次启动生效)=確定對選取主機啟用 TLS 傳輸嗎?\n(Linux 用戶端立即生效並斷線重連;Windows 用戶端下次啟動生效)
|
||||
确定取消选中主机的 TLS 传输吗?\n(Linux 客户端立即生效并断线重连;Windows 客户端下次启动生效)=確定取消選取主機的 TLS 傳輸嗎?\n(Linux 用戶端立即生效並斷線重連;Windows 用戶端下次啟動生效)
|
||||
服务端未启用 TLS 证书,无法切换客户端 TLS 传输=伺服器未啟用 TLS 憑證,無法切換用戶端 TLS 傳輸
|
||||
读取服务端 TLS 证书失败,无法下发=讀取伺服器 TLS 憑證失敗,無法下發
|
||||
白名单=白名單
|
||||
|
||||
Reference in new issue
Block a user