4 Commits
Author SHA1 Message Date
yuanyuanxianganddeepseek-flash b743de6747 Feat(client): add TLS transport to the macOS client
macOS shares the Linux transport: TlsChannel.h now dispatches __APPLE__ to
the OpenSSL implementation, so handshake, pinned trust anchor, reload and
removal all come from client/TlsChannelLinux.cpp. Only the platform glue
is new: ConfigDir() follows initConfigPaths (HOME, then getpwuid(), then
/tmp; no XDG) so the anchor sits next to config.conf, and ExeDir() uses
_NSGetExecutablePath.

First connect stays plaintext. The operator turns TLS on from the online
list: COMMAND_TLS_ENABLE carries the anchor PEM, COMMAND_TLS_DISABLE
removes it. macos/main.mm saves the anchor, calls TlsReload() and only
reconnects when the transport actually changed, so re-saving the same
anchor does not drop a live session. RES_TLS is filled from TlsEnabled()
and refreshed on every reconnect; fillLoginInfo clears szReserved first
now, because AddReserved appends and it runs twice on a group change.

CMake builds arm64 only (deployment target 11.0) and links Homebrew
openssl@3 statically when libcrypto.a is present, so the binary carries
no Homebrew path dependency. Not built or run on a Mac yet: the Apple
branch was syntax-checked under WSL and the login refresh probe-tested;
macos/README.txt has the build and verify steps.

Co-Authored-By: deepseek-flash
2026-11-14 11:43:30 +01:00
yuanyuanxianganddeepseek-flash 3d87ec6720 Fix(client): detach the receive thread instead of leaking one per connection
CloseHandle and SAFE_CLOSE_HANDLE are empty off Windows, so the POSIX
receive thread is never released: nothing detaches it and nothing joins
it. Every IOCPClient keeps one thread for good, and each screen, file,
shell or log sub-connection constructs a fresh IOCPClient. Once the leak
reaches RLIMIT_NPROC, pthread_create returns EAGAIN, std::thread throws,
and OnServerReceiving's catch(...) swallows it: every command that spawns
a worker goes quiet while COMMAND_SYSTEM keeps working. Observed on a Mac
after six weeks: 2048 threads against a 1333 limit.

Detach the thread right after creation so it is reclaimed when it
returns; the destructor still waits on m_bWorkThread, so nothing else
changes. Also log the pthread_create failure that used to be silent, and
publish S_STOP as the very last write in WorkThreadProc: the destructor
reads it as "thread is gone" and frees this, so the m_bIsRunning that
used to follow it could land in freed memory.

Two smaller fixes on the same sub-connection path:

- common/sub_conn_thread.h never called SetDefaultProto, so sub-connects
  fell back to plaintext TCP whatever g_SETTINGS.protoType said: behind a
  reverse proxy the packet dies before the master (no [ConnAuth] on the
  server, only "waiting for ack timed out" on the client). Android did.
- macos/main.mm and linux/main.cpp log the spawn before starting the
  worker and catch std::system_error, reporting e.code().value() rather
  than errno, which libc++/libstdc++ never set here. The macOS skeleton
  also reports ConnectServer failures and a null createHandler.

Co-Authored-By: deepseek-flash
2026-11-14 11:43:04 +01:00
yuanyuanxianganddeepseek-flash 80c7d1ed53 Fix(go): decode Windows host names with the system code page
The web console showed Chinese computer names as a run of U+FFFD.
ParseLoginInfo sent every string field through the UTF-8 decoder once a
client advertised CLIENT_CAP_UTF8, but szPCName and the OS string are not
covered by that bit: Windows fills them from gethostname(), a narrow API,
so they carry CP936/GBK even on modern clients. The MFC server decodes
these two fields with CP_ACP (HostJson.cpp::AnsiToUtf8), which is why the
Windows server and its web view were never affected.

A new DecodeLoginAnsiField picks by client type instead of capability:
LNX/MAC/macOS/APK are UTF-8 (they build the field from a UTF-8 host name
or, for Android, the device model), everything else is GBK. "macOS" is
what pre-1.0 macOS builds report; GetClientType sends "MAC" today and the
MFC WebService still accepts both. ASCII host names come out
byte-identical either way, and legacy clients keep the name they had.

Reserved keeps its capability-based decoding, so UTF-8 file paths and
locations are untouched; OS strings are ASCII in practice. The one case
that gets worse is a Windows machine running the "Beta: Use Unicode UTF-8"
locale, which will now mojibake there. Sniffing UTF-8 to cover it would
misfire on real GBK names -- 930 of 6763 GBK hanzi pass as a UTF-8
two-byte sequence, roughly 2% of two-character names -- so the
deterministic rule wins and the trade is written next to the function.

Tests cover GBK names from capable and legacy clients, UTF-8 names from
Linux, Android and legacy macOS, and Reserved still honoring the bit.

Co-Authored-By: deepseek-flash
2026-11-14 11:42:32 +01:00
yuanyuanxianganddeepseek-flash 9fadb58c76 Fix(client): rotate HELL header encoding across reconnects
A Release client drew one of the twelve HELL header encodings in the
constructor and kept it for life. The Go fallback server latches a type
from the first packet and only decodes None..V6, so every client that
drew V7..V10 could never log in to it — a third of them, at random, for
good.

The main connection now advances to the next type when it reconnects
after a connection that was never login-acked (CMD_MASTERSETTING), and
republishes the accepted type into CONNECT_ADDRESS::szFuture. A type that
did log in is kept, so a healthy client no longer churns through values
the fallback would reject. Sub-connections, including one-shot ones
(file/process/screen), inherit the published value at construction and
on every reconnect instead of rolling their own dice. Debug keeps its
None..V6-only range; the initial Release type now comes from
random_device rather than time() % N, which handed a whole batch started
in the same second the same value.

The slot sits at szFuture+16, after LOCAL_TEST_CLIENT_MAGIC, guarded by
static_asserts; it is memory-only and never persisted or sent. Swapping
the encoder is a single atomic function-pointer store, so the send and
receive threads see either the old or the new encoder and never a
dropped object.

Co-Authored-By: deepseek-flash
2026-11-13 16:47:53 +01:00
19 changed files with 776 additions and 76 deletions

No files matched your search

+3
View File
@@ -809,6 +809,9 @@ DWORD WINAPI StartClient(LPVOID lParam)
State& bExit(app.g_bExit);
IOCPClient *ClientObject = NewNetClient(&settings, bExit, pubIP);
if (nullptr == ClientObject) return -1;
// 主连接:登录被接受后发布头加密类型;上一条连接没被登录接受时,重连换下一种类型
// 轮转探测。其余 IOCPClient(文件/进程/屏幕等子连接)都跟随这里发布的值。
ClientObject->MarkMainLink();
CKernelManager* Manager = nullptr;
if (!app.m_bShared) {
+124 -9
View File
@@ -27,6 +27,7 @@ inline int WSAGetLastError()
#include "IOCPClient.h"
#include <assert.h>
#include <string>
#include <random>
#if USING_ZLIB
#include "zlib/zlib.h"
#define Z_FAILED(p) (Z_OK != (p))
@@ -197,6 +198,35 @@ bool IOCPClient::TryHandleAuthResponse(PBYTE buf, ULONG len)
}
// HELL 头加密可选类型数:Debug 版与服务端(含 Go fallback)对齐,只到 HeaderEncV6;
// Release 版保留全部类型,靠主连接重连轮转去命中后端支持的那几种。
static int HeaderEncCount()
{
#ifdef _DEBUG
return HeaderEncV6 + 1;
#else
return HeaderEncNum;
#endif
}
// 构造时的初始类型。原来直接 time(nullptr) % N:同一秒内启动的一批客户端会拿到
// 同一个类型,快速重连也反复取到同一个值。
// 不持有静态发生器:本函数会被多个并存实例(并发上线/分享)的构造线程调用,无共享
// 状态就无需加锁;random_device 个别平台在 /dev/urandom 不可用时会抛异常,退回时钟。
static int RandomHeaderEncIndex(int count)
{
unsigned v = 0;
try {
std::random_device rd;
v = rd();
} catch (...) {
// 极少数平台取不到 /dev/urandom 会抛异常:退回时钟(纳秒级,够打散同秒启动)。
v = (unsigned)std::chrono::steady_clock::now().time_since_epoch().count()
^ (unsigned)time(nullptr);
}
return (int)(v % (unsigned)count);
}
IOCPClient::IOCPClient(const State&bExit, bool exit_while_disconnect, int mask, CONNECT_ADDRESS* conn,
const std::string& pubIP, void* main) : g_bExit(bExit)
{
@@ -230,13 +260,24 @@ IOCPClient::IOCPClient(const State&bExit, bool exit_while_disconnect, int mask,
m_DataProcess = NULL;
m_ReconnectFunc = NULL;
m_masker = mask ? new HttpMask(DEFAULT_HOST) : new PkgMask();
#ifdef _DEBUG
auto enc = GetHeaderEncoder(HeaderEncType(time(nullptr) % (HeaderEncV6 + 1)));
#else
auto enc = GetHeaderEncoder(HeaderEncType(time(nullptr) % HeaderEncNum));
#endif
m_EncoderType = encoder;
m_Encoder = encoder ? new HellEncoder(enc, new XOREncoder16()) : new ProtocolEncoder();
if (encoder) {
const int count = HeaderEncCount();
int idx = -1;
if (conn) {
// 子连接优先继承主连接「已被当前后端接受」的类型(PublishHeaderEncoder)。
// 0 表示尚未发布,回退随机,保持原有的打散效果。
int published = GetHeaderEncSelect(conn);
if (published >= 1 && published <= count)
idx = published - 1;
}
if (idx < 0)
idx = RandomHeaderEncIndex(count);
m_headerEncIdx.store(idx);
m_Encoder = new HellEncoder(GetHeaderEncoder((HeaderEncType)idx), new XOREncoder16());
} else {
m_Encoder = new ProtocolEncoder();
}
#ifdef _WIN32
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
@@ -266,6 +307,52 @@ IOCPClient::IOCPClient(const State&bExit, bool exit_while_disconnect, int mask,
#endif
}
void IOCPClient::PrepareHeaderEncoderForConnect()
{
if (!m_EncoderType) {
return; // Shine:没有头加密函数可换
}
const int count = HeaderEncCount();
if (!m_bMainLink) {
// 子连接:跟随主连接最新发布的、已被当前后端接受的类型。一次性子连接(文件/
// 进程等只连一次)因此不会自己掷骰子撞上 Go fallback 不认识的 V7~V10。
// 取舍:后端切换(C++ 主控挂掉、Go fallback 接管)到主连接重连并重发布之间的
// 窗口里,子连接会拿旧值反复碰壁;主连接一发布新值就自愈。这里不自己轮转,是为
// 了让「一次性子连接只连一次」这种最常见的情形始终用主连接验证过的值。
int published = m_conn ? GetHeaderEncSelect(m_conn) : 0;
if (published >= 1 && published <= count) {
int idx = published - 1;
if (idx != m_headerEncIdx.load(std::memory_order_relaxed)) {
m_headerEncIdx.store(idx, std::memory_order_relaxed);
m_Encoder->SetHeaderEnc(GetHeaderEncoder((HeaderEncType)idx));
}
return;
}
// 主连接尚未发布(例如键盘子连接在主连接登录前就建好了):退化为轮转,见下。
}
// 第一次建连沿用构造时确定的类型(继承值或随机初值)。之后只在「上一条连接没有
// 被登录接受」时才换下一种:已被接受说明当前后端解析得了这个类型,重连沿用即可;
// 无故轮转只会在 Go fallback 上白丢几轮(V7~V10 会被它拒掉)。
// m_loginAcked 由 ConnectServer 在本函数**之后**才清零,所以这里读到的是上一条连接
// 的结论(见调用处注释)。
if (m_headerEncAttempts.fetch_add(1, std::memory_order_relaxed) > 0
&& !m_loginAcked.load(std::memory_order_acquire)) {
int idx = (m_headerEncIdx.load(std::memory_order_relaxed) + 1) % count;
m_headerEncIdx.store(idx, std::memory_order_relaxed);
m_Encoder->SetHeaderEnc(GetHeaderEncoder((HeaderEncType)idx));
}
}
void IOCPClient::PublishHeaderEncoder()
{
// 只有主连接、且确实在用 HELL 头加密时才有意义。
if (m_bMainLink && m_EncoderType && m_conn) {
SetHeaderEncSelect(m_conn, m_headerEncIdx.load(std::memory_order_relaxed));
}
}
void IOCPClient::SetMultiThreadCompress(int threadNum)
{
#if USING_CTX
@@ -443,6 +530,14 @@ BOOL ConnectWithTimeout(SOCKET sock, const struct sockaddr* addr, int timeout_se
BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
{
// 每次建连(含重连)先定下这次要用的 HELL 头加密函数。必须在建 socket / 启动收发
// 线程之前完成:后端只在每条连接的**第一个**包上识别并锁定头加密方式(Go 的
// parser.go 首包锁存,认不出就 ErrUnsupported 直接断开),换类型只对「下一条连接的
// 首包」有意义;此刻旧连接已断开,也就避开了与收发线程争用编码器对象。
// 注意顺序:PrepareHeaderEncoderForConnect 要读上一条连接的 m_loginAcked,故它必须是
// 本条连接清零登录标志**之前**的第一条语句。
PrepareHeaderEncoderForConnect();
// 登录确认标志只描述「当前这条连接」:任何一次新建连都先清零,避免上一条连接的
// 确认结果替新连接背书(协议切换的自动回退靠它判断新入口是否真的登录成功)。
m_loginAcked.store(false, std::memory_order_release);
@@ -638,7 +733,7 @@ BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
return FALSE;
}
m_useWs = true;
// 注意:这里不能读 m_useTls——无 TLS 的平台上(macOS/Android)它不存在;
// 注意:这里不能读 m_useTls——它只在定义了 YAMA_TLS_CHANNEL 的平台上存在;
// 本连接实际走的形态由 wsDegraded 区分:WSS 有锚走 TLS,没锚则明文回退。
Mprintf("[WS] WebSocket 已就绪: %s:%d%s%s\n", wsHost.c_str(), (int)port,
WS_UPGRADE_PATH, wsDegraded ? " (明文,等待信任锚)"
@@ -671,6 +766,17 @@ BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
pthread_t id = 0;
int ret = pthread_create(&id, nullptr, (void* (*)(void*))IOCPClient::WorkThreadProc, this);
if (ret == 0) {
// 必须 detach:POSIX 上 CloseHandle / SAFE_CLOSE_HANDLE 是空宏
// (common/commands.h:77-78),析构函数里的 SAFE_CLOSE_HANDLE(m_hWorkThread)
// 什么都不做,也没有任何地方 pthread_join 过这个线程。未 detach 的 pthread
// 退出后不会释放线程结构体和栈,于是**每个 IOCPClient 实例永久泄漏一个线程**
// —— 而子连接(屏幕/文件/终端/日志)每次点击都新建一个 IOCPClient。
// 泄漏累积到 RLIMIT_NPROC 附近后 pthread_create 开始返回 EAGAIN:
// 主连接因为已有线程还活着不受影响,但新开的子连接全部失败,
// 表现为「重启客户端就好、点按钮毫无反应」。detach 后线程退出即回收。
// 安全性:析构函数仍靠 m_bWorkThread 等待线程收尾;m_hWorkThread 在 POSIX 上
// 只当「线程已存在」的标志位用,从不被当作内核句柄解引用。
pthread_detach(id);
m_bWorkThread = S_RUN;
m_bIsRunning = TRUE;
// Store pthread_t so subsequent ConnectServer calls (reconnects) find
@@ -680,6 +786,11 @@ BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
// SAFE_CLOSE_HANDLE and CloseHandle are no-ops on Android, so the value
// is never dereferenced as a kernel handle.
m_hWorkThread = reinterpret_cast<HANDLE>(static_cast<uintptr_t>(id));
} else {
// pthread_create 直接返回错误码(不经 errno):EAGAIN(35)/EPERM(1) 基本就是
// 进程/用户的线程数到顶。这条路径原本完全静默——连接看起来「成功」了,
// 但没有收包线程,后续 ConnAuth 必然超时,日志里只剩一句"等待响应超时"。
Mprintf("[ERROR] pthread_create(WorkThread) failed: ret=%d\n", ret);
}
#endif
}
@@ -758,9 +869,13 @@ DWORD WINAPI IOCPClient::WorkThreadProc(LPVOID lParam)
}
SAFE_CLOSE_HANDLE(This->m_hWorkThread);
This->m_hWorkThread = NULL;
This->m_bWorkThread = S_STOP;
This->m_bIsRunning = FALSE;
delete[] szBuffer;
// 最后一步才发布 S_STOP:析构函数以「m_bWorkThread != S_RUN」判断线程已完全退出,
// 看到它之后就会释放成员并返回,调用方随即 delete this。反过来写(先 S_STOP 再
// m_bIsRunning)等于给析构函数一个提前放行的窗口——最后那句 m_bIsRunning 会写进
// 已释放的内存。此后本函数不得再读写 This 的任何成员。
This->m_bWorkThread = S_STOP;
return 0xDEAD;
}
@@ -841,7 +956,7 @@ VOID IOCPClient::OnServerReceiving(CBuffer* m_CompressedBuffer, char* szBuffer,
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
// macOS 没有 TlsChannel(TLS 已在 Windows/Linux/Android 客户端实现)
// 该平台没有 TlsChannel(YAMA_TLS_CHANNEL 未定义):没有传输层状态可打
Mprintf("[ERROR] Unknown header! this=%p bufLen=%lu, first 16 bytes: %s\n",
this, bufLen, buf.c_str());
#endif
+34 -5
View File
@@ -11,8 +11,8 @@
#pragma comment(lib,"ws2_32.lib")
#endif
// TLS 通道:Windows 走 Schannel,Linux 走 OpenSSL;macOS/Android 下该头为空,
// 且不定义 YAMA_TLS_CHANNEL,下方代码自动退回明文。
// TLS 通道:Windows 走 Schannel,Linux / Android / macOS 走 OpenSSL(TlsChannelLinux.cpp)。
// 其它平台该头为空,且不定义 YAMA_TLS_CHANNEL,下方代码自动退回明文。
#include "TlsChannel.h"
// WebSocket 传输(经反代 443 等受限端口接入)。头文件实现,各平台编译目标无需改动。
@@ -70,6 +70,8 @@ public:
}
virtual void Encode(unsigned char* data, int len, unsigned char* param = 0) {}
virtual void Decode(unsigned char* data, int len, unsigned char* param = 0) {}
// 只有 HellEncoder 有可替换的头加密函数;Shine 等实现忽略。
virtual void SetHeaderEnc(EncFun) {}
virtual EncFun GetHeaderEncoder() const
{
return nullptr;
@@ -79,21 +81,27 @@ public:
class HellEncoder : public ProtocolEncoder
{
private:
EncFun m_HeaderEnc;
// 原子量:主连接重连时会在发送线程/接收线程可能同时使用编码器的时机更换头加密函数,
// 只换函数指针(零分配、零释放),读方永远拿到新旧之一,不会 UAF。
std::atomic<EncFun> m_HeaderEnc;
Encoder *m_BodyEnc;
public:
HellEncoder(EncFun head, Encoder *body)
{
m_HeaderEnc = head;
m_HeaderEnc.store(head, std::memory_order_relaxed);
m_BodyEnc = body;
}
~HellEncoder()
{
SAFE_DELETE(m_BodyEnc);
}
virtual void SetHeaderEnc(EncFun enc) override
{
m_HeaderEnc.store(enc, std::memory_order_relaxed);
}
virtual HeaderFlag GetHead() const override
{
return ::GetHead(m_HeaderEnc);
return ::GetHead(m_HeaderEnc.load(std::memory_order_relaxed));
}
virtual int GetHeadLen() const override
{
@@ -292,6 +300,17 @@ public:
m_subConnAuthClientID = clientID;
}
// 标记本对象是主连接。只有 StartClient 里 NewNetClient() 拿到的那一个会调用;
// 只有主连接会在登录被接受后发布头加密类型、并在上一条连接未被登录接受时轮转
// 探测,子连接一律跟随发布值(见 PrepareHeaderEncoderForConnect / PublishHeaderEncoder)。
void MarkMainLink() { m_bMainLink = true; }
// 把当前 HELL 头加密类型发布到 CONNECT_ADDRESS 的共享槽位(仅主连接有效)。
// 必须在服务端**真正接受登录之后**调用(CMD_MASTERSETTING),不能在 ConnectServer
// 返回时就调:握手成功不代表后端解析得了这个头(Go fallback 是读到登录包才拒绝),
// 而且子连接的 ConnectServer 也会走到那里,会用自己乱撞的值覆盖发布值。
void PublishHeaderEncoder();
// 内部:在收到的数据帧分发到 manager 之前,尝试识别并消费 TOKEN_CONN_AUTH ack。
// 仅在我们正在等待 auth 响应时(m_authPending=true)才消费;否则透传给 manager。
bool TryHandleAuthResponse(PBYTE buf, ULONG len);
@@ -334,6 +353,12 @@ public:
virtual VOID Disconnect(); // 函数支持 TCP/UDP
protected:
// 每次建连前调整 HELL 头加密函数:主连接上一条没被登录接受时换下一种类型轮转探测,
// 子连接跟随主连接已发布的类型。必须在建 socket / 启动收发线程之前完成——后端只在
// 每条连接的**第一个**包上识别并锁定头加密方式(Go 首包锁存、认不出即断开),所以
// 换类型只对「下一条连接的首包」生效;这一步同时读上一条连接的 m_loginAcked,
// 因此必须先于 ConnectServer 里的登录标志清零。
void PrepareHeaderEncoderForConnect();
virtual int ReceiveData(char* buffer, int bufSize, int flags)
{
// WebSocket 传输:字节流在 WS 帧里,帧层自己处理 TLS(WSS)或裸 socket(WS)
@@ -428,6 +453,10 @@ protected:
bool m_exit_while_disconnect;
PkgMask* m_masker;
BOOL m_EncoderType;
// HELL 头加密运行态(见 PrepareHeaderEncoderForConnect / PublishHeaderEncoder)
std::atomic<int> m_headerEncIdx{0}; // HeaderEncType 下标(仅 HELL 有意义)
std::atomic<int> m_headerEncAttempts{0}; // ConnectServer 已调用次数
bool m_bMainLink = false; // StartClient 的主连接标记
std::string m_sLocPublicIP;
CONNECT_ADDRESS *m_conn = NULL;
+5 -1
View File
@@ -1444,8 +1444,12 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
// 登录已被服务端接受:服务端把本机加入在线列表后才下发 MasterSettings
// (2015RemoteDlg.cpp::SendMasterSettings(ctx, ...) 的登录路径)。协议切换的
// 自动回退靠这个信号撤销,而不是只看连接是否建立——连接建立只说明握手完成。
if (m_ClientObject)
if (m_ClientObject) {
m_ClientObject->SetLoginAcked(true);
// 后端确实按当前头加密类型解析成功了,发布给后续创建的子连接继承
// (只有主连接会走到 CMD_MASTERSETTING,见 PublishHeaderEncoder)。
m_ClientObject->PublishHeaderEncoder();
}
if (ulLength > MasterSettingsOldSize) {
memcpy(&m_settings, szBuffer + 1, ulLength > sizeof(MasterSettings) ? sizeof(MasterSettings) : MasterSettingsOldSize);
if (m_settings.Signature[0] && m_LoginSignature.empty()) {
+14 -9
View File
@@ -6,7 +6,8 @@
//
// 选型:
// - Windows:Schannel(原生 SSPI),零第三方依赖;secur32.lib / crypt32.lib 为系统库。
// - Linux:OpenSSL(构建链已因 libsign 链接 libcrypto,另加 libssl 即可)。
// - Linux / macOS:OpenSSL(Linux 构建链已因 libsign 链接 libcrypto,另加 libssl 即可;
// macOS 需 Homebrew openssl@3,见 macos/CMakeLists.txt)。
// 两者都是单向 TLS:客户端只校验服务端证书链到固定的信任锚,不提供客户端证书,
// 客户端身份仍由隧道内登录(V1 PwdHmac / V2 ECDSA)承担;均不校主机名(客户端按 IP
// 连接),不做吊销检查——与 Windows 版既有语义保持一致。
@@ -16,11 +17,12 @@
// Send/Recv 对上下文的使用由 m_ctxMtx 互斥,避免重连线程释放上下文时与使用线程产生
// use-after-free。本对象作为 IOCPClient 的值成员存在,析构时释放上下文。
//
// 平台范围:_WIN32(Schannel)、Linux 与 Android(OpenSSL)有实现;macOS 不含任何内容,
// 客户端维持明文。这些平台都通过 YAMA_TLS_CHANNEL 宏告知调用方「本平台有 TLS 通道」。
// 平台范围:_WIN32(Schannel)、Linux / Android / macOS(OpenSSL)有实现。这些平台都通过
// YAMA_TLS_CHANNEL 宏告知调用方「本平台有 TLS 通道」。
// Android 复用 Linux 的 OpenSSL 实现(TlsChannelLinux.cpp),唯一差异是信任锚目录改为
// App 私有 filesDir(由 TlsSetAnchorDir 注入),语义(单向 TLS1.2 钉扎、fail-closed、
// 热重载)与 Linux 完全一致。
// 热重载)与 Linux 完全一致。macOS 同样复用这份 OpenSSL 实现且不改目录规则:
// ~/.config/ghost/yama-ca.pem 与 macOS 客户端现有的 config.conf 目录一致。
#pragma once
#if defined(_WIN32)
@@ -135,7 +137,7 @@ private:
std::vector<BYTE> m_pending; // 已解密、未交付给应用层的明文
};
#elif defined(__linux__) // 含 Android:__ANDROID__ 同时定义 __linux__
#elif defined(__linux__) || defined(__APPLE__) // Android 同时定义 __linux__;macOS 走同一份 OpenSSL 实现
#define YAMA_TLS_CHANNEL 1
@@ -152,15 +154,18 @@ bool TlsEnabled();
// (fail-closed),不得静默回退明文。线程安全、幂等。
bool TlsLoadError();
// Windows 版按目标地址区分「用不用内嵌锚」。Linux / Android 客户端没有内嵌锚概念(生成器
// 只往 Windows 镜像里写锚块),信任锚一律是配置文件,故这里忽略目标地址,与进程级开关等价。
// Windows 版按目标地址区分「用不用内嵌锚」。Linux / Android / macOS 客户端没有内嵌锚概念
// (生成器只往 Windows 镜像里写锚块),信任锚一律是配置文件,故这里忽略目标地址,与进程级
// 开关等价。
inline bool TlsEnabledFor(const std::string&, const std::string&) { return TlsEnabled(); }
inline bool TlsLoadErrorFor(const std::string&, const std::string&) { return TlsLoadError(); }
// 服务端下发信任锚(COMMAND_TLS_ENABLE):把 PEM 正文写入信任锚文件,原子替换、权限 0600。
// 写入前先解析验证,不是合法证书就整包拒绝。目录按平台:
// Linux:$XDG_CONFIG_HOME/ghost/yama-ca.pem(默认 ~/.config/ghost/yama-ca.pem,无 HOME
// 时退回程序目录);
// Linux:$XDG_CONFIG_HOME/ghost/yama-ca.pem(默认 ~/.config/ghost/yama-ca.pem);
// macOS:~/.config/ghost/yama-ca.pem(与 macos/main.mm 的 config.conf 同目录,不读
// XDG_CONFIG_HOME;HOME 兜底也逐字对齐 initConfigPaths:HOME → getpwuid → /tmp);
// Linux 无 HOME 时退回程序目录;
// Android:App 私有 filesDir/yama-ca.pem(目录由 TlsSetAnchorDir 注入)。
// 落盘后用 TlsReload() 立即生效(Windows 客户端在 COMMAND_TLS_ENABLE 里调用同一个
// TlsReload(),各平台行为一致)。
+45 -7
View File
@@ -1,4 +1,4 @@
// TlsChannelLinux.cpp — 见 TlsChannel.h 头注释。Linux 与 Android 编译(共用 OpenSSL 实现)。
// TlsChannelLinux.cpp — 见 TlsChannel.h 头注释。Linux / Android / macOS 编译(共用 OpenSSL 实现)。
//
// 与 Windows 的 Schannel 实现语义对齐:
// - 单向 TLS 1.2(min=max=1.2,与 SP_PROT_TLS1_2_CLIENT 及两套服务端一致);
@@ -9,7 +9,7 @@
// 与 Windows 实现的差异:OpenSSL 自己管理 TLS 记录缓冲,不需要 m_raw/m_pending;
// 一次性交付不出去的明文留在 SSL 内部,由 SSL_has_pending()/SSL_pending() 暴露给
// 接收线程在 select 前优先消费。
#if defined(__linux__) // 含 Android:__ANDROID__ 同时定义 __linux__
#if defined(__linux__) || defined(__APPLE__) // Android 同时定义 __linux__;macOS 走同一份实现
#include "TlsChannel.h"
@@ -24,6 +24,7 @@
#include <cerrno>
#include <chrono>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <fstream>
@@ -37,6 +38,11 @@
#include <sys/types.h>
#include <unistd.h>
#if defined(__APPLE__)
#include <mach-o/dyld.h> // _NSGetExecutablePath
#include <pwd.h> // getpwuid:与 macos/main.mm 的 HOME 兜底保持一致
#endif
namespace {
const char* const kAnchorName = "yama-ca.pem";
@@ -55,27 +61,58 @@ std::string g_anchorDir; // 信任锚目录,由 TlsSetAnchorDir
// 配置目录:
// Linux:与 LinuxConfig 相同规则($XDG_CONFIG_HOME/ghost 或 ~/.config/ghost);
// macOS:固定 ~/.config/ghost(跟随 macos/main.mm 的 config.conf 位置,不吃 XDG_CONFIG_HOME);
// Android:App 私有 filesDir(TlsSetAnchorDir 注入),无「程序目录」回退。
std::string ConfigDir()
{
#ifdef __ANDROID__
return g_anchorDir;
#else
const char* home = getenv("HOME");
#if defined(__APPLE__)
// macOS 不看 XDG_CONFIG_HOME:macos/main.mm 的 initConfigPaths 把 config.conf 固定
// 放在 ~/.config/ghost,信任锚必须跟着它走,否则同一台机器会出现两份配置目录。
// HOME 兜底顺序也与 initConfigPaths 逐字对齐(HOME → getpwuid()->pw_dir → /tmp):
// 手工做成 launchd daemon 时 launchd 不导出 HOME,只查 HOME 会让锚落到「程序目录」,
// 而 config.conf 在 pw_dir 下——升级/重装 app bundle 时锚跟着被删,客户端静默退回明文,
// 而服务端仍以为这台是 TLS。
if (!home || !home[0]) {
struct passwd* pw = getpwuid(getuid());
if (pw && pw->pw_dir && pw->pw_dir[0])
home = pw->pw_dir;
}
if (!home || !home[0])
home = "/tmp";
return std::string(home) + "/.config/ghost";
#else
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";
#endif
#endif
}
// 可执行文件所在目录(readlink /proc/self/exe,失败返回空)。Android 无此概念,返回空。
// 可执行文件所在目录(失败返回空)。仅用作「无 HOME」时的回退位置。Android 无此概念。
std::string ExeDir()
{
#ifdef __ANDROID__
#if defined(__ANDROID__)
return std::string();
#elif defined(__APPLE__)
// macOS 没有 /proc/self/exe。_NSGetExecutablePath 返回的路径可能含符号链接/相对成分,
// 这里只取所在目录、不做规范化——用途只是找同目录的 yama-ca.pem,与 Linux 分支一致。
// 注意 size 是 in/out:缓冲区不足时返回 -1,不能读返回后的内容。
char buf[4096];
uint32_t size = sizeof(buf);
if (_NSGetExecutablePath(buf, &size) != 0)
return std::string();
char* slash = strrchr(buf, '/');
if (!slash)
return std::string();
*slash = '\0';
return std::string(buf);
#else
char buf[4096];
ssize_t n = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
@@ -91,7 +128,8 @@ std::string ExeDir()
}
// 信任锚候选路径(按优先级),只返回已经存在的那个:
// 1) $XDG_CONFIG_HOME/ghost/yama-ca.pem(默认 ~/.config/ghost/yama-ca.pem)
// 1) ConfigDir()/yama-ca.pem(Linux 默认 ~/.config/ghost,macOS 固定 ~/.config/ghost,
// Android 为 App filesDir)
// 2) 可执行文件同目录 yama-ca.pem(兼容手工投递,与 Windows 的 exe 同名文件回退一致)
bool FindAnchorPath(std::string& out)
{
@@ -600,4 +638,4 @@ bool TlsChannel::HasPending() const
return SSL_pending(m_ssl) > 0 || SSL_has_pending(m_ssl) == 1;
}
#endif // __linux__(含 Android)
#endif // __linux__ / __APPLE__(Linux 含 Android;macOS)
+37
View File
@@ -10,6 +10,7 @@
#include <ctime>
#include <chrono>
#include <climits>
#include <cstddef> // offsetof:CONNECT_ADDRESS::szFuture 运行态槽位的对齐断言
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
@@ -1157,6 +1158,42 @@ inline bool IsLocalTestClient(const CONNECT_ADDRESS* conn)
sizeof(LOCAL_TEST_CLIENT_MAGIC) - 1) == 0;
}
// szFuture 前 sizeof(LOCAL_TEST_CLIENT_MAGIC) 字节被上面的本地测试标记占用;其后从
// HEADER_ENC_SELECT_OFFSET 起放一个运行态字段(只在内存里有效,不落盘、不参与分享/
// 转移序列化):
// int 头加密下标 + 1,0 = 尚未发布(烘焙的 EXE 里 szFuture 全 0)
//
// 用途:主连接收到 CMD_MASTERSETTING(登录已被后端接受)后,把当前 HELL 头加密类型写
// 进来;文件/进程/屏幕等子连接在构造和重连时优先继承它,避免自己随机到 Go fallback
// 服务端尚未实现的 HeaderEncV7~V10。该值只当「提示」用:读方必须做范围校验,坏值回退
// 随机(下标越界会读穿 GetHeaderEncoder 的方法表)。
//
// 跨线程:写方是主连接的接收线程(CKernelManager::OnReceive → PublishHeaderEncoder),
// 读方是各子连接自己的线程(构造/重连),这里**不做同步**,也不保证读到最新值——
// 读到旧值等价于「尚未发布」,回退随机,行为正确。前提是该槽位只承载这种提示语义:
// 不要拿它做控制逻辑,也不要放大成多字段协议。目标平台(x86/x64/ARM64)上 4 字节
// 对齐的读写不会撕裂,配合上面的范围校验即可。
#define HEADER_ENC_SELECT_OFFSET sizeof(LOCAL_TEST_CLIENT_MAGIC)
static_assert(HEADER_ENC_SELECT_OFFSET % sizeof(int) == 0, "头加密运行态槽位需 4 字节对齐");
static_assert(sizeof(((CONNECT_ADDRESS*)0)->szFuture) >= HEADER_ENC_SELECT_OFFSET + sizeof(int),
"CONNECT_ADDRESS::szFuture 空间不足");
static_assert(offsetof(CONNECT_ADDRESS, szFuture) % alignof(int) == 0,
"CONNECT_ADDRESS::szFuture 需 4 字节对齐");
inline int GetHeaderEncSelect(const CONNECT_ADDRESS* conn)
{
int value = 0;
if (conn) memcpy(&value, conn->szFuture + HEADER_ENC_SELECT_OFFSET, sizeof(value));
return value;
}
inline void SetHeaderEncSelect(CONNECT_ADDRESS* conn, int index)
{
if (!conn) return;
int value = index + 1;
memcpy(conn->szFuture + HEADER_ENC_SELECT_OFFSET, &value, sizeof(value));
}
#define FOREVER_RUN 2
// 客户端程序线程信息结构体, 包含5个成员:
+6 -1
View File
@@ -17,6 +17,7 @@
#endif
#include <iostream>
#include <cstdio> // fprintf:macOS 非 ObjC 翻译单元的 Mprintf 走 stderr
#include <fstream>
#include <mutex>
#include <queue>
@@ -390,7 +391,11 @@ inline const char* getFileName(const char* path)
#ifdef __OBJC__
#define Mprintf(format, ...) NSLog(@"%@", [NSString stringWithFormat:@(format), ##__VA_ARGS__])
#else
#define Mprintf(format, ...) printf(format, ##__VA_ARGS__)
// 非 ObjC 翻译单元(IOCPClient/FileManager/TlsChannel 等)没有 NSLog,只能写流。
// 必须写 stderr:macos/main.mm 把 stderr 重定向到 /tmp/ghost.log(daemon 与 App bundle
// 两种启动方式都做,App bundle 还设了 CFLOG_FORCE_STDERR 让 NSLog 也落到同一文件);
// stdout 在 App bundle / login item 启动时没人接收,写过去的日志会直接丢掉。
#define Mprintf(format, ...) fprintf(stderr, format, ##__VA_ARGS__)
#endif
#elif defined(__ANDROID__)
#include <android/log.h>
+23
View File
@@ -47,6 +47,18 @@ inline void RunSubConnThread(const char* threadName, CreateFn createHandler, OnR
void* clientAddr = ClientObject.get();
Mprintf(">>> Enter %s [%p]\n", threadName, clientAddr);
// 传输协议必须显式喂进去,否则子连接与主连接走的不是同一条路:
// Linux/macOS 的 IOCPClient 不带 m_conn,ConnectServer 里协议来源是
// m_defaultProto(默认 -1 = 明文 TCP)。主连接在 main 里已 SetDefaultProto
// (macos/main.mm / linux/main.cpp),子连接漏掉这一步时,配成 WS/WSS 的客户端
// 会出现「主连接正常、所有子连接静默按明文直连」——经反代/HTTP 代理接入时,
// 明文 TCP 在到达主控之前就被丢掉,服务端连一条 [ConnAuth] 都看不到,
// 而客户端只会卡在 "[ConnAuth] 等待响应超时"。见 main.mm 里同一段注释。
ClientObject->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
Mprintf(">>> %s: proto=%d (%s:%d)\n", threadName,
(int)(unsigned char)g_SETTINGS.protoType,
g_SETTINGS.ServerIP(), g_SETTINGS.ServerPort());
// 子连接:开启 auth。Linux/macOS IOCPClient 不带 m_conn,显式传入 g_myClientID。
ClientObject->EnableSubConnAuth(true, g_myClientID);
@@ -61,8 +73,19 @@ inline void RunSubConnThread(const char* threadName, CreateFn createHandler, OnR
Sleep(1000);
// 清除回调,防止重连线程访问已销毁的 handler
ClientObject->setManagerCallBack(nullptr, nullptr, nullptr);
} else {
// createHandler 返回 nullptr = 本机侧初始化失败(如 macOS 无录屏权限)。
// 子连接已经建立、鉴权也已通过,这里不关掉的话它会一直挂着,服务端那边
// 表现为「子连接在线但永远不发首包」,而客户端日志里原本一个字都没有。
Mprintf("*** %s: handler init failed, dropping sub-connection ***\n", threadName);
}
} else if (S_CLIENT_NORMAL == g_bExit) {
// 只有 g_bExit 仍是 NORMAL 时才算真失败(TCP 连接、握手、ConnAuth 任一环节,
// ConnectServer 内部已各自打过具体原因)。这里补一条归属明确的收尾日志,
// 否则「子连接没建起来」在日志里只剩一行 Leave,无从判断卡在哪一步。
Mprintf("*** %s: ConnectServer failed ***\n", threadName);
}
// g_bExit 已置位 = 客户端正在退出,子连接没建起来是预期行为,不打错误日志。
Mprintf(">>> Leave %s [%p]\n", threadName, clientAddr);
} catch (const std::exception& e) {
Mprintf("*** %s exception: %s ***\n", threadName, e.what());
+24 -6
View File
@@ -1,6 +1,6 @@
# 传输层单向 TLS 加密设计(按需加密)
> 版本:v0.8 · 状态:**Go 服务端 + Windows/Linux/Android 客户端已实现并验证;Linux/Android 客户端支持下发即时热切换;MFC 主控端见 `TransportTLS_MFCServer_Design.md`;macOS 未接入** · 日期:2026-11-11(Android 客户端接入 + 热切换)
> 版本:v0.9 · 状态:**Go 服务端 + Windows/Linux/Android 客户端已实现并验证;Linux/Android 客户端支持下发即时热切换;macOS 客户端已按同一模式实现(2026-11-14,待 Mac 实机构建验证);MFC 主控端见 `TransportTLS_MFCServer_Design.md`** · 日期:2026-11-14(macOS 客户端接入)
> 目标:让 YAMA 设备端口(TCP 6543)在继续兼容老客户端(明文/XOR)的同时,允许新客户端在拿到证书后按需开启**单向 TLS** 加密传输。
> 本期范围:**Go 服务端(`server/go`)+ Windows 客户端 + Linux 客户端 + Android 客户端**。
>
@@ -23,8 +23,7 @@
- 不做 **mTLS / 客户端证书**:单向 TLS 不验证客户端证书,客户端身份仍由隧道内的现有登录(`PwdHmac` V1 / `ECDSA` V2)承担。
- 不做传输层 PSK(`YAMA_TRANSPORT_KEY`)方案——本设计改用证书,更贴合「颁发证书」的运维模型。
- 不改应用层协议(flag 帧格式 / XOR / zstd),不做「TLS 内去掉 XOR」的二次精简(后续可选)。
- Windows 客户端**不做**加密开关的运行时热切换(证书只在进程启动时读取一次,改配置需重启——这正是需求)。Linux / Android 客户端例外:服务端下发 166/167 后立即重载信任锚并重连切换(§6.6 / §6.7),语义差异见该两节。
- macOS 客户端的 TLS 接入不在本期(Linux / Android 客户端已按同一模式接入,见 §6.6 / §6.7)。
- Windows 客户端**不做**加密开关的运行时热切换(证书只在进程启动时读取一次,改配置需重启——这正是需求)。Linux / Android / macOS 客户端例外:服务端下发 166/167 后立即重载信任锚并重连切换(§6.6 / §6.7 / §6.8),语义差异见该三节。
- 不做 **MFC 服务端(`server/2015Remote`)的 TLS 接入**——本期只做 Go 服务端(`server/go`),MFC 主控端延后到阶段 3。
## 2. 现状与复用
@@ -194,6 +193,8 @@ Linux 无注册表,信任锚按:① `$XDG_CONFIG_HOME/ghost/yama-ca.pem`(
Android 同样无注册表,信任锚为 App 私有 `context.filesDir/yama-ca.pem`(目录由 `TlsSetAnchorDir()` 在 `nativeInit` 注入,见 §6.7),无程序目录回退;存在即视为已配置、fail-closed。与 Linux 共用 `client/TlsChannelLinux.cpp` 实现。
macOS 无注册表,信任锚为 `~/.config/ghost/yama-ca.pem`(与 `macos/main.mm` 的 `config.conf` 同目录;**不看 `XDG_CONFIG_HOME`**,保持与 macOS 客户端既有配置路径一致)→ ② 程序目录(`_NSGetExecutablePath`)`yama-ca.pem`。存在即视为已配置、fail-closed。与 Linux/Android 共用 `client/TlsChannelLinux.cpp` 实现(见 §6.8)。
### 6.2 TLS 栈选型(已定:Schannel)
- **已选 Schannel(Windows 原生 SSPI)**:零第三方依赖/零额外 DLL 部署,`secur32.lib`/`crypt32.lib` 均为系统库(`secur32.lib` 已在 `CFFmpegH264Encoder.cpp:38` 链接)。
@@ -230,7 +231,7 @@ Schannel 流模式(`ISC_REQ_STREAM`)下,`DecryptMessage` 会把输入的
### 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__` → OpenSSL,含 Android,见 §6.7),Windows 分支内容不变;实现文件为 `client/TlsChannelLinux.cpp`。`YAMA_TLS_CHANNEL` 宏标注「本平台有 TLS 通道」,`IOCPClient` 用它替代原先的 `#ifdef _WIN32`,因此主连接与子连接共用同一接线点。macOS 不定义该宏,维持明文。
- **代码组织**:`client/TlsChannel.h` 按平台分派(`_WIN32` → Schannel,`__linux__`(含 Android,见 §6.7)与 `__APPLE__`(macOS,见 §6.8)→ OpenSSL),Windows 分支内容不变;实现文件为 `client/TlsChannelLinux.cpp`。`YAMA_TLS_CHANNEL` 宏标注「本平台有 TLS 通道」,`IOCPClient` 用它替代原先的 `#ifdef _WIN32`,因此主连接与子连接共用同一接线点。
- **语义对齐**:`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 解析一遍,不是合法证书就整包拒绝并保留原状态。
@@ -241,7 +242,7 @@ Schannel 流模式(`ISC_REQ_STREAM`)下,`DecryptMessage` 会把输入的
- 热重载遇到坏锚时**保留原状态**并记日志,不把正在工作的客户端打死(下次启动仍按 fail-closed 语义)。
- 重连由 `DataProcess`(接收线程)只置 `g_needReconnect` 标志,由主心跳线程 `Disconnect()` 后走外层重连循环——避免在接收线程里关 socket 与主线程发送竞争。
- **代价**:此刻若正处于远程桌面/文件传输会话,主连接重建会中断该会话(子连接随之失效)。这是「立即生效」的固有代价。
- **上报**:登录 `szReserved[19]`(`RES_TLS`)填 `TlsEnabled() ? 1 : 0`,主控端主机信息显示 Y/N。热切换后重连会重新登录,登录前用 `RefreshLoginTls()` 刷新该字段,主控端在线列表的 TLS 列随之翻转。
- **上报**:登录 `szReserved[19]`(`RES_TLS`)填 `TlsEnabled() ? 1 : 0`,主控端主机信息显示 Y/N。热切换后重连会重新登录,登录前用 `RefreshLoginTls()` 刷新该字段,主控端在线列表的 TLS 列随之翻转。Android 同。
### 6.7 Android 客户端实现(OpenSSL,2026-11-11)
@@ -252,6 +253,22 @@ Schannel 流模式(`ISC_REQ_STREAM`)下,`DecryptMessage` 会把输入的
- **OpenSSL 构建**:Android 的 `libsign.a` 用便携纯 C SHA256、不含 OpenSSL,故需新交叉编译 `libssl.a`/`libcrypto.a`。`android/build_openssl_android.sh`(已并入 `build_android_libs.ps1`,可 `-OpenSslOnly` 单跑)用 NDK clang + MSYS2 perl/make 按 ABI(arm64-v8a / armeabi-v7a / x86 / x86_64,API 21)构建 OpenSSL 3.5.0 静态库(`no-shared no-apps no-legacy` 等裁剪);产物落 `app/src/main/cpp/lib/<ABI>/`,`opensslconf.h` 各架构不同故头文件也按 ABI 存放。CMake 链接 `libssl.a`+`libcrypto.a`,并用 `-Wl,--exclude-libs,ALL` 不让静态库符号泄出 `libyama.so`(与 Java 层 Conscrypt 隔离;JNI 入口来自目标文件,不受影响)。
- **Windows 构建坑(已解决)**:Git for Windows 的精简 perl 缺 Configure 所需模块,且其 bash/env 会抢占 PATH——跨 MSYS 运行时传子进程丢环境变量(Configure 拿不到 `ANDROID_NDK_ROOT`),脚本改用 `#!/bin/bash` 并把 MSYS2 `/usr/bin` 置顶;NDK 自带原生 make 不认 Makefile 里的 `/c/...` 路径,须用 MSYS2 make(`pacman -S make`)。
### 6.8 macOS 客户端实现(OpenSSL,2026-11-14)
- **选型 / 代码组织**:复用 Linux/Android 的 OpenSSL 实现。`client/TlsChannel.h` 的平台分支由 `__linux__` 放宽为 `__linux__ || __APPLE__`,`TlsChannelLinux.cpp` 的编译守卫同步放宽(该文件本就是 OpenSSL + POSIX,无 Linux 专有调用);`YAMA_TLS_CHANNEL` 随之在 macOS 生效,主连接/子连接共用与 Linux 相同的接线点(`IOCPClient`)。**服务端零改动**。
- **平台差异点(都在 `TlsChannelLinux.cpp` 内条件编译)**:
- **配置目录**:`ConfigDir()` 在 Apple 上**不读 `XDG_CONFIG_HOME`**,HOME 兜底顺序与 `macos/main.mm` 的 `initConfigPaths` 逐字对齐(`HOME` → `getpwuid()->pw_dir` → `/tmp`),最终都是 `<home>/.config/ghost`——否则信任锚和 `config.conf` 会落在两个目录(launchd daemon 不导出 `HOME` 时尤其明显:锚落到程序目录,重装 app bundle 时跟着被删,客户端静默退回明文而服务端仍以为它是 TLS)。
- **程序目录回退**:`ExeDir()` 用 `_NSGetExecutablePath`(`<mach-o/dyld.h>`)截取目录;Linux 继续用 `/proc/self/exe`,Android 仍返回空。
- **`SIGPIPE`**:`macos/main.mm` 启动时已 `signal(SIGPIPE, SIG_IGN)`(WSS 引入时加的),TLS 写入对端已关时不会直接杀掉进程。
- **热切换接线(`macos/main.mm`)**:与 Linux 同一套语义。`DataProcess` 收到 `COMMAND_TLS_ENABLE`(166) → `TlsTrustAnchorSave()`;`COMMAND_TLS_DISABLE`(167) → `TlsTrustAnchorRemove()`;两者随后都走 `ApplyTlsAnchorChange()`:`TlsReload()` 重建 `SSL_CTX`,只在传输方式真的变化(明文↔TLS)时置 `g_needReconnect`(接收线程只置标志),主心跳循环每秒检查、`Disconnect()` 后由外层重连循环用新传输方式重连。仅换锚不打断现有会话。
- **上报**:登录 `szReserved[19]`(`RES_TLS`)填 `TlsEnabled() ? 1 : 0`;重连登录前用 `RefreshLoginTls()` 刷新(`logInfo` 启动时填一次、之后复用)。顺带修掉一个既有缺陷:分组变更重发登录时 `fillLoginInfo()` 会被再次调用,而 `AddReserved()` 是追加语义,原先会把整套保留字段再拼一遍,导致服务端按 `LOGIN_RES` 下标读到错位/重复字段——现在 `fillLoginInfo()` 入口先清空 `szReserved`。
- **构建(`macos/CMakeLists.txt` / `build.sh`)**:
- 源码列表加入 `client/TlsChannelLinux.cpp`;链接 `OpenSSL::SSL`、`OpenSSL::Crypto`。
- Homebrew 的 `openssl@3` 不在 CMake 默认搜索路径,`CMakeLists.txt` 自动探测 `/opt/homebrew/opt/openssl@3`(及其它常见前缀),找不到直接 `FATAL_ERROR` 并提示 `brew install openssl@3`,也可 `-DOPENSSL_ROOT_DIR=...` 指定。
- 有静态库(`libssl.a`/`libcrypto.a`)时优先静态链接(`OPENSSL_USE_STATIC_LIBS`),避免发布包还得让目标 Mac 装 Homebrew OpenSSL;只有动态库时给 `WARNING`,需自行把 dylib 放进 `Contents/Frameworks`。
- 目标为 **arm64 单架构**(Homebrew OpenSSL 只有本机架构,保留 x86_64 slice 会链接失败)、部署目标 macOS 11.0。`build.sh` 通过命令行显式传 `-DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_OSX_DEPLOYMENT_TARGET=11.0`——这两个是 CMake **cache 变量**,在已存在的 `build/` 目录里改了 `CMakeLists.txt` 也不会生效,必须命令行覆盖或删目录重建。
- **注意**:macOS 客户端在线升级仍不支持(服务端 `OnOnlineUpdate` 无 MAC 分支),升级 TLS 相关代码需重新 `macos/build.sh` 并按 `macos/install.sh` 部署(会重置 TCC 授权)。
## 7. 兼容矩阵
| 客户端 | 服务端行为 | 结果 |
@@ -337,6 +354,7 @@ Android 客户端:信任锚写入 App 私有 `filesDir/yama-ca.pem`(经 166/
- **阶段 2(Windows 客户端)**:证书检测 + TLS 栈 + fail-closed。
- **阶段 2b(Linux 客户端)**:OpenSSL 实现,复用同一接线点与协议语义(2026-10-28 完成)。
- **阶段 2c(Android 客户端)**:复用 Linux OpenSSL 实现,NDK 按 ABI 交叉编译 OpenSSL,热切换(2026-11-11 完成)。
- **阶段 2d(macOS 客户端)**:复用 Linux OpenSSL 实现(`__APPLE__` 分支 + `_NSGetExecutablePath`),Homebrew OpenSSL 静态链接,热切换(2026-11-14 完成代码,待 Mac 实机验证)。
- **阶段 3(MFC 服务端 `server/2015Remote`,延后)**:与 Go 服务端同款的 TLS 检测 + 解包接入。设计稿见 `docs/TransportTLS_MFCServer_Design.md`。
- **回滚**:服务端清空 `YAMA_TLS_CERT/KEY` 即回到纯明文;客户端删除注册表 `tls_cert` 值(或 `yama-ca.pem` 文件)即回明文。
@@ -345,4 +363,4 @@ Android 客户端:信任锚写入 App 私有 `filesDir/yama-ca.pem`(经 166/
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 接入排期~~ → **Linux(2026-10-28)、Android(2026-11-11)已接入**(均 OpenSSL、支持热切换);macOS 待定(需 Security.framework 或自带 OpenSSL)。
4. ~~Linux / macOS / Android 客户端的 TLS 接入排期~~ → **Linux(2026-10-28)、Android(2026-11-11)、macOS(2026-11-14)已接入**(均 OpenSSL、支持热切换)。
+2 -2
View File
@@ -112,7 +112,7 @@ Host 头同理:用**配置里的地址(域名)**,而不是解析后的 I
| 有锚但加载失败(损坏/为空) | 拒绝连接(fail-closed)——管理员已「颁发」证书,不能静默回退明文 |
| 无锚 + `PROTO_WS` | 明文(本来如此) |
| 有锚 + `PROTO_WS` | **仍是明文**(显式选择的形态,见下) |
| 平台无 TLS(macOS 未定义 `YAMA_TLS_CHANNEL`)+ `PROTO_WSS` | 直接断开并打日志:没有热切换路径,回退只会让人误以为在加密 |
| 平台无 TLS(未定义 `YAMA_TLS_CHANNEL`)+ `PROTO_WSS` | 直接断开并打日志:没有热切换路径,回退只会让人误以为在加密 |
| WS 握手失败 | 断开,`Mprintf` 里带上服务端返回的状态行 |
回退的判据是「本机**根本没有**信任锚」这一可观测状态,而不是握手中途失败——TLS 握手
@@ -415,7 +415,7 @@ server {
升级线程里才有。若这是硬性合规要求,需单独评估(本特性未改变这一点,只是让它的漏检更
容易发生)。
- 裸 `PROTO_WS` 是明文,只适合内网或回环(nginx 已在同一台机器上终止 TLS 的情形用 WSS 即可)。
- macOS 客户端没有 TLS 实现,只能选 `PROTO_WS`(明文),走不了 443(Linux / Android 已有 TLS,见 `TransportTLS_Design.md` §6.6 / §6.7)。
- macOS 客户端自 2026-11-14 起也有 TLS(与 Linux/Android 同一 OpenSSL 实现,见 `TransportTLS_Design.md` §6.8),WSS 与 Linux 行为一致;更早的 macOS 构建仍只能选 `PROTO_WS`(明文),走不了 443。
- 经反代接入时地址只应填**一个域名**(多地址取第一个做 Host/SNI)。
- 不改应用协议、不改 MCP、不改 Web 控制台。
+26 -10
View File
@@ -9,6 +9,7 @@
#include <string.h>
#include <termios.h>
#include <thread>
#include <system_error> // std::system_error:SpawnSubConnWorker 捕获线程创建失败
#include <fcntl.h>
#include <atomic>
#include <mutex>
@@ -647,6 +648,26 @@ static void ActivityReportThread()
g_activityReportsInFlight.fetch_sub(1, std::memory_order_relaxed);
}
// 子连接 worker 的唯一启动点(与 macos/main.mm 的 SpawnSubConnWorker 同语义)。
// 线程创建失败(RLIMIT_NPROC 到顶时 pthread_create 返回 EAGAIN/EPERM,std::thread
// 构造抛 std::system_error)必须在这里接住:否则异常穿过 DataProcess 落到
// OnServerReceiving 的 catch(...),日志里只剩一行笼统的
// "[ERROR] OnServerReceiving catch an error",同一批 recv 里的其它完整包也会被丢弃。
// 表现是「点了终端/桌面/文件毫无反应,连收到命令的日志都没有」。
static void SpawnSubConnWorker(const char* name, void* (*entry)(void*))
{
Mprintf("** Received '%s' command, spawning worker ***\n", name);
try {
std::thread(entry, nullptr).detach();
} catch (const std::system_error& e) {
// pthread_create 的返回值被 libc++/libstdc++ 直接包进 error_code,errno 不可信
Mprintf("*** spawn '%s' worker FAILED: %s (code=%d) ***\n",
name, e.what(), e.code().value());
} catch (const std::exception& e) {
Mprintf("*** spawn '%s' worker FAILED: %s ***\n", name, e.what());
}
}
int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
{
if (szBuffer == nullptr || ulLength == 0)
@@ -662,22 +683,17 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
Mprintf("*** [%p] Received Bye-Bye command ***\n", user);
g_bExit = S_CLIENT_EXIT;
} else if (szBuffer[0] == COMMAND_SHELL) {
std::thread(ShellworkingThread, nullptr).detach();
Mprintf("** [%p] Received 'SHELL' command ***\n", user);
SpawnSubConnWorker("SHELL", ShellworkingThread);
} else if (szBuffer[0] == COMMAND_SCREEN_SPY) {
std::thread(ScreenworkingThread, nullptr).detach();
Mprintf("** [%p] Received 'SCREEN_SPY' command ***\n", user);
SpawnSubConnWorker("SCREEN_SPY", ScreenworkingThread);
} else if (szBuffer[0] == COMMAND_SYSTEM) {
std::thread(SystemManagerThread, nullptr).detach();
Mprintf("** [%p] Received 'SYSTEM' command ***\n", user);
SpawnSubConnWorker("SYSTEM", SystemManagerThread);
} else if (szBuffer[0] == COMMAND_LIST_DRIVE) {
std::thread(FileManagerThread, nullptr).detach();
Mprintf("** [%p] Received 'LIST_DRIVE' command ***\n", user);
SpawnSubConnWorker("LIST_DRIVE", FileManagerThread);
} else if (szBuffer[0] == COMMAND_QUERY_LOG) {
// 与 Windows 端一致:回日志必须开子连接。服务端取走首包后 CancelIO 关的是
// 子连接;若回在主连接上,被关掉的就是主连接本身。
std::thread(ClientLogThread, nullptr).detach();
Mprintf("** [%p] Received 'QUERY_LOG' command ***\n", user);
SpawnSubConnWorker("QUERY_LOG", ClientLogThread);
} else if (szBuffer[0] == COMMAND_QUERY_ACTIVITY) {
// 历史活动:主连接一次性快照(无子连接),有桌面走窗口采样,无桌面走登录+命令记录。
// 已经有报表在飞就丢掉这一次(服务端每主机单飞行,连点也只是重复请求)
+49 -4
View File
@@ -4,11 +4,16 @@ project(ghost_macos)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# macOS deployment target
set(CMAKE_OSX_DEPLOYMENT_TARGET "10.13" CACHE STRING "Minimum macOS version")
# macOS deployment target。arm64 的底线就是 11.0(Apple Silicon 首发系统),
# 与 Homebrew openssl@3 自身的最低版本一致,避免链接时出现 "built for newer" 告警。
set(CMAKE_OSX_DEPLOYMENT_TARGET "11.0" CACHE STRING "Minimum macOS version")
# Universal Binary (Intel + Apple Silicon)
set(CMAKE_OSX_ARCHITECTURES "x86_64;arm64" CACHE STRING "Build architectures")
# 只构建 Apple Silicon。仓库里发布过的 macos/ghost 一直是 arm64-only(universal 设置从未
# 真正落地),且 Homebrew 的 OpenSSL 是单架构——保留 x86_64 slice 会让链接直接失败。
# 将来真要支持 Intel Mac,应单独用 x86_64 的 OpenSSL 构建一份,而不是把这里改回 universal。
# 注意 CMAKE_OSX_ARCHITECTURES 是 cache 变量:旧 build 目录里存的值不会因这里改字面量而
# 更新,build.sh 因此显式传 -DCMAKE_OSX_ARCHITECTURES=arm64。
set(CMAKE_OSX_ARCHITECTURES "arm64" CACHE STRING "Build architectures (arm64 only)")
include_directories(../)
include_directories(../client)
@@ -19,6 +24,9 @@ set(SOURCES
main.mm
../client/Buffer.cpp
../client/IOCPClient.cpp
# TLS 传输(OpenSSL 实现,与 Linux/Android 共用)。文件名叫 Linux 是历史原因,
# 平台守卫为 __linux__ || __APPLE__;macOS 的差异只有 ExeDir() 用 _NSGetExecutablePath。
../client/TlsChannelLinux.cpp
../client/sign_shim_unix.cpp
ScreenHandler.mm
InputHandler.mm
@@ -49,6 +57,41 @@ find_library(COREVIDEO_FRAMEWORK CoreVideo REQUIRED)
find_library(ACCELERATE_FRAMEWORK Accelerate REQUIRED)
find_library(ICONV_LIBRARY iconv REQUIRED)
# ---- OpenSSL(TLS 传输,见 client/TlsChannelLinux.cpp)----
# macOS 不自带 OpenSSL。优先用 Homebrew 的 openssl@3;也可显式指定
# cmake .. -DOPENSSL_ROOT_DIR=/path/to/openssl
# Apple Silicon 的 Homebrew 前缀是 /opt/homebrew,Intel 是 /usr/local。
if(NOT OPENSSL_ROOT_DIR)
foreach(_openssl_candidate
/opt/homebrew/opt/openssl@3
/usr/local/opt/openssl@3
/opt/homebrew/opt/openssl
/usr/local/opt/openssl)
if(EXISTS "${_openssl_candidate}/include/openssl/ssl.h")
set(OPENSSL_ROOT_DIR "${_openssl_candidate}")
break()
endif()
endforeach()
endif()
if(NOT OPENSSL_ROOT_DIR)
message(FATAL_ERROR
"找不到 OpenSSL。先执行: brew install openssl@3\n"
"或显式指定: cmake .. -DOPENSSL_ROOT_DIR=/opt/homebrew/opt/openssl@3")
endif()
# 有静态库就静态链接:产物保持单文件,install.sh 不需要打包 dylib 或修 @rpath。
# Homebrew 的 openssl@3 同时装 .a 和 .dylib;只有动态库时这里退化为动态链接并告警,
# 那种情况下发布前必须把 libssl/libcrypto dylib 一并放进 .app 的 Contents/Frameworks。
if(EXISTS "${OPENSSL_ROOT_DIR}/lib/libssl.a" AND EXISTS "${OPENSSL_ROOT_DIR}/lib/libcrypto.a")
set(OPENSSL_USE_STATIC_LIBS TRUE)
else()
message(WARNING
"OpenSSL 静态库不存在(${OPENSSL_ROOT_DIR}/lib/libssl.a),将动态链接;"
"发布前请确认目标 Mac 装有同一份 OpenSSL,或把 dylib 放进 Contents/Frameworks。")
endif()
find_package(OpenSSL REQUIRED)
message(STATUS "OpenSSL: ${OPENSSL_VERSION} (${OPENSSL_INCLUDE_DIR})")
target_link_libraries(ghost PRIVATE
${COCOA_FRAMEWORK}
${COREGRAPHICS_FRAMEWORK}
@@ -68,6 +111,8 @@ target_link_libraries(ghost PRIVATE
# libsign.a 内部使用 macOS CommonCrypto(HMAC-SHA256),CCHmac 在 libSystem
# 中已被 Cocoa/CoreFoundation 等链接自动引入,故此处无需额外 framework
"${CMAKE_SOURCE_DIR}/lib/libsign.a"
OpenSSL::SSL
OpenSSL::Crypto
)
# Compiler flags
+27 -1
View File
@@ -4,6 +4,12 @@ macOS Remote Desktop Client
Prerequisites:
1. Xcode Command Line Tools: xcode-select --install
2. CMake: brew install cmake
3. OpenSSL (TLS transport): brew install openssl@3
CMake 自动探测 /opt/homebrew/opt/openssl@3,也可用
cmake .. -DOPENSSL_ROOT_DIR=/path/to/openssl 指定。
构建目标是 Apple Silicon (arm64) 单架构:Homebrew 的 OpenSSL 只有本机架构,
保留 x86_64 slice 会链接失败。Intel Mac 需另建 x86_64 的 OpenSSL 单独构建。
Build:
chmod +x build.sh
@@ -11,7 +17,7 @@ Build:
Or manually:
mkdir build && cd build
cmake ..
cmake .. -DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_OSX_DEPLOYMENT_TARGET=11.0
make
Run:
@@ -21,6 +27,26 @@ Configuration:
Server address is configured in main.mm (g_SETTINGS variable).
Modify before building if needed.
TLS Transport:
Default is plaintext on first connect. The controller's host right-click menu
("TLS 传输") sends the trust anchor; the client stores it at
~/.config/ghost/yama-ca.pem, hot-reloads and reconnects over TLS 1.2
(fail-closed, pinned to that anchor). "取消TLS" deletes the file and
reconnects in plaintext. Existing sessions survive only if the transport does
not change (replacing the certificate keeps TLS).
Verify after building:
otool -L build/bin/ghost | grep -i ssl # 期望无输出:OpenSSL 已静态链接
tail -f /tmp/ghost.log
Startup prints one of:
[TLS] transport on first connect: plaintext (no trust anchor)
[TLS] transport on first connect: TLS (trust anchor present)
Clicking "TLS 传输" should log "TLS transport switched to TLS, reconnecting";
the host's TLS column in the online list then shows Y. "取消TLS" logs
"switched to plaintext" and the column flips back to N.
If the log says "trust anchor exists but failed to load", the client refuses
to connect (fail-closed) until the anchor is fixed or removed.
Permissions Required:
1. Screen Recording - System Settings > Privacy & Security > Screen Recording
2. Accessibility - System Settings > Privacy & Security > Accessibility
+6 -1
View File
@@ -27,8 +27,13 @@ mkdir -p build
cd build
# Configure
# 架构与最低系统版本显式传:两者都是 CMake 的 cache 变量,旧 build 目录里可能还存着
# universal / 10.13 的旧值,只改 CMakeLists.txt 不会生效(arm64 + Homebrew OpenSSL
# 是单架构组合,留着 x86_64 slice 会链接失败)。
echo "Configuring..."
cmake .. -DCMAKE_BUILD_TYPE=Release
cmake .. -DCMAKE_BUILD_TYPE=Release \
-DCMAKE_OSX_ARCHITECTURES=arm64 \
-DCMAKE_OSX_DEPLOYMENT_TARGET=11.0
# Build
echo ""
+150 -10
View File
@@ -15,8 +15,12 @@
#import <memory>
#import <string>
#import <map>
#import <vector>
#import <cstring> // strncpy(RefreshLoginTls 改写 szReserved)
#import <system_error>
#import "../client/IOCPClient.h"
#include "../client/TlsChannel.h" // TLS 传输(信任锚保存/热重载),随 IOCPClient 一起定义 YAMA_TLS_CHANNEL
#define XXH_INLINE_ALL
#include "../common/xxhash.h"
#include "../common/rtt_estimator.h"
@@ -37,6 +41,10 @@
// Global state
static std::atomic<bool> g_running(true);
static std::atomic<bool> g_needResendLogin(false); // 分组变更后需要重发登录信息
// 传输方式热切换(服务端 COMMAND_TLS_ENABLE/DISABLE 改了信任锚)后需要重建连接。
// DataProcess 跑在接收线程上,直接关 socket 会和主线程的发送竞争,所以只置标志,
// 由主心跳循环择机 Disconnect 并重连(与 linux/main.cpp 的 g_needReconnect 同语义)。
static std::atomic<bool> g_needReconnect(false);
// Client ID (calculated from system info, used by ScreenHandler)
uint64_t g_myClientID = 0;
@@ -495,6 +503,11 @@ static void fillLoginInfo(LOGIN_INFOR& info)
// Token is set in constructor
info.bToken = TOKEN_LOGIN;
// 分组变更后会带着同一个 logInfo 再调一次本函数。AddReserved 是「追加」,不清空
// 就会把整套保留字段再拼一遍,服务端按 LOGIN_RES 下标取值,看到的是重复/错位的
// 字段。这里先把保留区清空,让本函数可重入。
info.szReserved[0] = '\0';
// OS Version
std::string osVer = getMacOSVersion();
strncpy(info.OsVerInfoEx, osVer.c_str(), sizeof(info.OsVerInfoEx) - 1);
@@ -611,11 +624,13 @@ static void fillLoginInfo(LOGIN_INFOR& info)
}
info.AddReserved(std::to_string(g_myClientID).c_str());
// PID / 文件大小 / TLS:macOS 暂不上报,占位保持位置(服务端按 LOGIN_RES 下标取值,
// PID / 文件大小:macOS 暂不上报,占位保持位置(服务端按 LOGIN_RES 下标取值,
// 少发一项会让后面所有字段前移)。
info.AddReserved("");
info.AddReserved("");
info.AddReserved("");
// [19] RES_TLS:与 Linux 一致,有信任锚即 1。服务端在线列表的 TLS 列取这个值;
// 热切换后重连重发登录,务必用 RefreshLoginTls 刷新成当前状态。
info.AddReserved(TlsEnabled() ? 1 : 0);
// [20] RES_UPTIME:登录时刻的进程已运行秒数,服务端据此算「启动信息」里的时长
info.AddReserved((int)getProcessUptimeSeconds());
@@ -626,6 +641,39 @@ static void fillLoginInfo(LOGIN_INFOR& info)
osVer.c_str(), hostname.c_str(), info.dwCPUMHz, pubIP.c_str(), g_myClientID);
}
// [[19] RES_TLS] 是「当前」传输状态的快照,服务端在线列表的 TLS 列就取这个值。
// logInfo 只在启动时填一次、之后每条连接复用,因此热切换后重连时必须刷新它,
// 否则列里会一直显示切换前的状态。szReserved 是按 '|' 位置解析的,这里逐字段
// 拆开、只改第 [19] 项再拼回去(不能用 AddReserved,它只会往后追加)。
// 只在主线程调用(与 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';
}
// ============== Signal Handling ==============
// 注意:signal handler 内不能调 NSLog/Mprintf(NSLog 走 Foundation 锁,
@@ -755,6 +803,53 @@ void* ClientLogworkingThread(void* /*param*/)
return NULL;
}
// 子连接 worker 线程的唯一启动点。
//
// 顺序是有意为之:先把「收到命令」打出来,再 spawn。原先 Mprintf 写在
// std::thread(...).detach() 之后,一旦线程创建失败(pthread_create 返回
// EAGAIN/EPERM,进程线程数到顶、或受宿主环境限制),std::thread 构造函数抛
// std::system_error,异常会穿过 DataProcess 落到 OnServerReceiving 的 catch(...),
// 客户端日志里只剩一行笼统的 "[ERROR] OnServerReceiving catch an error":
// 「点了终端/桌面/文件毫无反应,而且连一条收到命令的日志都没有」正是这样产生的
// ——坏的三个功能恰好全都 spawn 线程,好的 SYSTEM/WSLIST 恰好都不 spawn。
static void SpawnSubConnWorker(const char* name, void* (*entry)(void*))
{
Mprintf("** Received '%s' command, spawning worker ***\n", name);
try {
std::thread(entry, nullptr).detach();
} catch (const std::system_error& e) {
// 线程创建失败只会抛 system_error,code() 里就是 pthread_create 的返回值
// (EAGAIN=35 / EPERM=1)。这里不能读 errno:libc++ 是把 pthread_create 的
// 返回值直接包成 error_code 抛出,并不设置 errno,读到的会是无关的旧值。
Mprintf("*** spawn '%s' worker FAILED: %s (code=%d) ***\n",
name, e.what(), e.code().value());
} catch (const std::exception& e) {
Mprintf("*** spawn '%s' worker FAILED: %s ***\n", name, e.what());
}
}
// 信任锚已落盘/已删除:热重载 TLS 状态,必要时请求主循环重建连接。
// 只在传输方式真正变化(明文↔TLS)时重连;仅换证书(仍是 TLS)不打断现有会话,
// 新锚从下一条新连接开始生效。与 linux/main.cpp 的 ApplyTlsAnchorChange 同语义。
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)
@@ -771,21 +866,17 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
g_bExit = S_CLIENT_EXIT;
g_running = false; // Stop main loop to prevent reconnection
} else if (szBuffer[0] == COMMAND_SHELL) {
std::thread(ShellworkingThread, nullptr).detach();
Mprintf("** [%p] Received 'SHELL' command ***\n", user);
SpawnSubConnWorker("SHELL", ShellworkingThread);
} else if (szBuffer[0] == COMMAND_SCREEN_SPY) {
std::thread(ScreenworkingThread, nullptr).detach();
Mprintf("** [%p] Received 'SCREEN_SPY' command ***\n", user);
SpawnSubConnWorker("SCREEN_SPY", ScreenworkingThread);
} else if (szBuffer[0] == COMMAND_SYSTEM) {
Mprintf("** [%p] Received 'SYSTEM' command ***\n", user);
} else if (szBuffer[0] == COMMAND_LIST_DRIVE) {
std::thread(FileManagerworkingThread, nullptr).detach();
Mprintf("** [%p] Received 'LIST_DRIVE' command ***\n", user);
SpawnSubConnWorker("LIST_DRIVE", FileManagerworkingThread);
} else if (szBuffer[0] == COMMAND_QUERY_LOG) {
// 与 Windows 端一致:回日志必须开子连接(服务端取走首包后 CancelIO 关的是
// 子连接;若回在主连接上,被关掉的就是主连接本身)。
std::thread(ClientLogworkingThread, nullptr).detach();
Mprintf("** [%p] Received 'QUERY_LOG' command ***\n", user);
SpawnSubConnWorker("QUERY_LOG", ClientLogworkingThread);
} else if (szBuffer[0] == COMMAND_C2C_PREPARE) {
// C2C 准备接收通知
FileTransferV2::HandleC2CPrepare(szBuffer, ulLength, nullptr);
@@ -866,6 +957,31 @@ 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/Linux 一致:szBuffer+1 起为 PEM 正文)。
// 落盘到 ~/.config/ghost/yama-ca.pem 后热重载,传输方式真正变化时由主循环重连。
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 {
Mprintf("** [%p] Received unimplemented command: %d ***\n", user, int(szBuffer[0]));
}
@@ -931,6 +1047,15 @@ int main(int argc, const char* argv[])
loadConfig();
NSLog(@"Config loaded from %s", g_configPath.c_str());
// 传输方式由信任锚文件决定(服务端右键「TLS 传输」才会写入 ~/.config/ghost/yama-ca.pem)。
// 启动时打一行,排查「首次连接为什么/为什么不加密」不用去猜。
if (TlsLoadError()) {
Mprintf("[TLS] trust anchor exists but failed to load; connections will be refused (fail-closed)\n");
} else {
Mprintf("[TLS] transport on first connect: %s\n",
TlsEnabled() ? "TLS (trust anchor present)" : "plaintext (no trust anchor)");
}
// Check permissions
NSLog(@"Checking permissions...");
@@ -989,9 +1114,15 @@ int main(int argc, const char* argv[])
Sleep(5000);
continue;
}
// 上一条连接断掉时若还挂着「切换传输」的请求,这条连接已经是按新信任锚
// 建立的了(ConnectServer 现读 TlsEnabled),标志已过时——不清掉会让心跳
// 循环刚进去就再断一次,白白抖动一轮。
g_needReconnect.store(false);
// 进入新连接,重置服务端身份校验状态
ClientAuth::OnNewConnection();
// 本条连接可能是热切换信任锚后重建的:TLS 标志按当前状态重算,再发登录。
RefreshLoginTls(logInfo);
ClientObject->SendLoginInfo(logInfo.Speed(clock() - c));
// 心跳保活循环:定时发送心跳包,服务端回复后动态更新 RTT
@@ -1006,10 +1137,19 @@ int main(int argc, const 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 transport change\n");
ClientObject->Disconnect();
break;
}
if (!ClientObject->IsRunning() || !ClientObject->IsConnected() || g_bExit != S_CLIENT_NORMAL)
break;
+1 -1
View File
@@ -5185,7 +5185,7 @@ void CMy2015RemoteDlg::OnExperimentTlsEnable()
return;
}
// 二次确认:避免误点就切换被控端 TLS。
// 两平台都是立即生效:客户端收到命令后落盘信任锚(Windows 注册表 / Linux 配置文件)、
// 客户端都是立即生效:收到命令后落盘信任锚(Windows 注册表 / Linux、macOS 配置文件)、
// 热重载 TLS 状态(各平台 TlsChannel 的 TlsReload)并断开重连,正在进行的远程会话会中断。
if (IDYES != MessageBoxL(_T("确定对选中主机启用 TLS 传输吗?\n"
"(客户端立即生效并断线重连,正在进行的远程会话会中断)"),
+46 -9
View File
@@ -541,15 +541,51 @@ type LoginInfo struct {
Reserved string // Contains additional info separated by |
}
// DecodeLoginAnsiField decodes a LOGIN_INFOR text field that is *not* covered
// by CLIENT_CAP_UTF8 (computer name, OS string). On Windows those are filled
// from narrow Win32/CRT APIs — gethostname() at client/LoginServer.cpp:380 —
// and carry the system code page (CP936/GBK on Chinese installs) even when the
// client advertises UTF-8 support; the capability bit only promises UTF-8 for
// the protocol string fields it lists (active window, window titles, file
// paths). The MFC server decodes these same fields with CP_ACP
// (HostJson.cpp::AnsiToUtf8), which is why a Chinese computer name renders
// correctly there and showed up as "����" in the Go server's web console.
// POSIX and Android clients build the field as UTF-8, so keep their bytes.
// "macOS" is the client-type string of pre-1.0 macOS builds (GetClientType
// returns "MAC" today; the MFC server still accepts both, see
// WebService.cpp's dblclick branch). Those builds also send UTF-8 names, so
// they must not fall into the GBK path or the same login decodes differently
// in the Go server than in the C++ one.
//
// GBK is hard-coded because the Go server has no equivalent of the server
// machine's CP_ACP; that matches the MFC deployment everyone runs (a Chinese
// server). Consequence worth knowing: a Windows machine with the "Beta: Use
// Unicode UTF-8" locale option sends UTF-8 here too and will show mojibake —
// the MFC server mangles that case as well, and sniffing UTF-8 instead would
// misfire on real GBK names (measured: 930 of 6763 GBK hanzi validate as a
// UTF-8 two-byte sequence, so ~2% of two-character host names would be
// misread), so the deterministic rule is the safer side of the trade.
func DecodeLoginAnsiField(data []byte, clientType string) string {
switch clientType {
case "LNX", "MAC", "macOS", "APK":
return Utf8CleanString(data)
}
return GbkToUTF8(data)
}
// ParseLoginInfo parses LOGIN_INFOR from data.
//
// Encoding: text fields are GBK on legacy Windows clients and UTF-8 on modern
// clients that set CLIENT_CAP_UTF8 (always on for LNX / MAC). Picking the
// wrong codec mangles non-ASCII characters — e.g. a German location string
// "Nürnberg" sent as UTF-8 (4E C3 BC 72 ...) and force-decoded as GBK turns
// into mojibake. The heartbeat path already honors this via DecodeClientString
// (see cmd/main.go handleHeartbeat); ParseLoginInfo previously did not, so
// every login string from a UTF-8 client was being misread.
// Encoding: Reserved (file path, location, ...) is GBK on legacy Windows
// clients and UTF-8 on modern clients that set CLIENT_CAP_UTF8 (always on for
// LNX / MAC). Picking the wrong codec mangles non-ASCII characters — e.g. a
// German location string "Nürnberg" sent as UTF-8 (4E C3 BC 72 ...) and
// force-decoded as GBK turns into mojibake. The heartbeat path already honors
// this via DecodeClientString (see cmd/main.go handleHeartbeat); ParseLoginInfo
// previously did not, so every login string from a UTF-8 client was misread.
//
// Computer name and OS use a different rule: they are ANSI on Windows
// regardless of the capability bit (see DecodeLoginAnsiField), so they are
// decoded by client type, not by capability.
//
// To get encoding right we have a chicken-and-egg problem: capability lives
// in ModuleVersion (offset 164) and clientType lives in Reserved field 0
@@ -600,11 +636,12 @@ func ParseLoginInfo(data []byte) (*LoginInfo, error) {
// Now decode every user-text field with the client's actual codec.
decode := func(b []byte) string { return DecodeClientString(b, capability, clientType) }
// Computer name / OS: ANSI on Windows whatever the capability says.
if len(data) >= OffsetOsVerInfoEx+156 {
info.OsVerInfo = decode(data[OffsetOsVerInfoEx : OffsetOsVerInfoEx+156])
info.OsVerInfo = DecodeLoginAnsiField(data[OffsetOsVerInfoEx:OffsetOsVerInfoEx+156], clientType)
}
if len(data) >= OffsetPCName+240 {
info.PCName = decode(data[OffsetPCName : OffsetPCName+240])
info.PCName = DecodeLoginAnsiField(data[OffsetPCName:OffsetPCName+240], clientType)
}
if len(data) >= OffsetMasterID+20 {
info.MasterID = decode(data[OffsetMasterID : OffsetMasterID+20])
+154
View File
@@ -0,0 +1,154 @@
package protocol
import (
"bytes"
"encoding/binary"
"strings"
"testing"
)
// buildLoginInfo lays out a synthetic LOGIN_INFOR packet. The C++ struct is
// fixed-width and NUL-padded; fields not touched here stay zero.
func buildLoginInfo(moduleVersion, clientType string, pcName []byte) []byte {
b := make([]byte, OffsetReserved+512)
b[0] = TokenLogin
copy(b[OffsetModuleVersion:], moduleVersion)
copy(b[OffsetPCName:OffsetPCName+240], pcName)
copy(b[OffsetReserved:], clientType)
return b
}
// A Chinese Windows host name arrives as ANSI (CP936/GBK) bytes: the client
// fills LOGIN_INFOR.szPCName from gethostname(), a narrow Win32 API, whatever
// CLIENT_CAP_UTF8 says (client/LoginServer.cpp:380). The MFC server converts
// this field with CP_ACP, so it renders correctly; the Go server used to feed
// it to the UTF-8 decoder for every modern client, turning each GBK byte into
// U+FFFD ("����") in the web console.
func TestLoginInfoGBKHostNameFromUTF8CapableClient(t *testing.T) {
name := "我的电脑/研发组"
raw := buildLoginInfo("Oct 20 2025-0006", "EXE", UTF8ToGBK(name))
info, err := ParseLoginInfo(raw)
if err != nil {
t.Fatalf("ParseLoginInfo: %v", err)
}
if info.PCName != name {
t.Fatalf("PCName = %q, want %q", info.PCName, name)
}
}
func TestLoginInfoGBKHostNameFromLegacyClient(t *testing.T) {
name := "张三的电脑"
raw := buildLoginInfo("Dec 19 2024", "EXE", UTF8ToGBK(name))
info, err := ParseLoginInfo(raw)
if err != nil {
t.Fatalf("ParseLoginInfo: %v", err)
}
if info.PCName != name {
t.Fatalf("PCName = %q, want %q", info.PCName, name)
}
}
// POSIX clients build szPCName from gethostname() on a UTF-8 system, so their
// non-ASCII names must not be run through the GBK decoder.
func TestLoginInfoUTF8HostNameFromLinuxClient(t *testing.T) {
name := "Nürnberg-PC"
raw := buildLoginInfo("Oct 20 2025-0006", "LNX", []byte(name))
info, err := ParseLoginInfo(raw)
if err != nil {
t.Fatalf("ParseLoginInfo: %v", err)
}
if info.PCName != name {
t.Fatalf("PCName = %q, want %q", info.PCName, name)
}
}
// The APK client sends the Android device model as UTF-8.
func TestLoginInfoUTF8HostNameFromAndroidClient(t *testing.T) {
name := "小米14"
raw := buildLoginInfo("Oct 20 2025-8007", "APK", []byte(name))
info, err := ParseLoginInfo(raw)
if err != nil {
t.Fatalf("ParseLoginInfo: %v", err)
}
if info.PCName != name {
t.Fatalf("PCName = %q, want %q", info.PCName, name)
}
}
// Pre-1.0 macOS builds report the client type as "macOS" (current builds send
// "MAC"); their host names are UTF-8 too and must not be GBK-decoded.
func TestLoginInfoUTF8HostNameFromLegacyMacClient(t *testing.T) {
name := "München-Mac"
raw := buildLoginInfo("Dec 19 2024", "macOS", []byte(name))
info, err := ParseLoginInfo(raw)
if err != nil {
t.Fatalf("ParseLoginInfo: %v", err)
}
if info.PCName != name {
t.Fatalf("PCName = %q, want %q", info.PCName, name)
}
}
// Reserved must keep following CLIENT_CAP_UTF8: RES_FILE_PATH is UTF-8 on
// modern clients (client/LoginServer.cpp:411) while legacy clients sent
// CP_ACP, and the location field is UTF-8 for modern clients too.
func TestLoginInfoReservedStillHonorsCapability(t *testing.T) {
path := `C:\Users\张三\Desktop\样本.exe`
reserved := strings.Join([]string{
"EXE", // 0 client type
"64", // 1 system bits
"8", // 2 cpu
"16", // 3 memory
path, // 4 file path (UTF-8 on capable clients)
"?", // 5
"2025-01-02", // 6 install time
"?", // 7
"64", // 8 program bits
"", // 9
"北京/朝阳", // 10 location (UTF-8 on capable clients)
"1.2.3.4", // 11 public ip
"v1.0", // 12 version
"user", // 13 username
"0", // 14 admin
}, "|")
raw := buildLoginInfo("Oct 20 2025-0006", "", UTF8ToGBK("PC"))
copy(raw[OffsetReserved:], reserved)
// clientType itself lives in field 0 of the very same Reserved bytes.
if !bytes.HasPrefix(raw[OffsetReserved:], []byte("EXE|")) {
t.Fatal("test fixture broken")
}
info, err := ParseLoginInfo(raw)
if err != nil {
t.Fatalf("ParseLoginInfo: %v", err)
}
if got := info.GetReservedField(ResFieldFilePath); got != path {
t.Fatalf("file path = %q, want %q", got, path)
}
if got := info.GetReservedField(ResFieldClientLoc); got != "北京/朝阳" {
t.Fatalf("location = %q, want %q", got, "北京/朝阳")
}
}
func TestLoginInfoBinaryFieldsUnaffected(t *testing.T) {
raw := buildLoginInfo("Oct 20 2025-0006", "EXE", UTF8ToGBK("PC"))
binary.LittleEndian.PutUint32(raw[OffsetCPUMHz:], 3600)
raw[OffsetWebCamExist] = 1
binary.LittleEndian.PutUint32(raw[OffsetSpeed:], 123)
info, err := ParseLoginInfo(raw)
if err != nil {
t.Fatalf("ParseLoginInfo: %v", err)
}
if info.CPUMHz != 3600 || !info.WebCamExist || info.Speed != 123 {
t.Fatalf("binary fields = %d/%v/%d", info.CPUMHz, info.WebCamExist, info.Speed)
}
if info.PCName != "PC" {
t.Fatalf("PCName = %q", info.PCName)
}
}