Reuse the Linux OpenSSL TlsChannel implementation (platform guard widened to __linux__); the trust anchor lives in the app-private filesDir, injected via TlsSetAnchorDir in nativeInit before the connection thread starts. COMMAND_TLS_ENABLE/DISABLE save/remove the anchor, hot-reload and reconnect only when the transport actually changes, so the master menu takes effect within seconds without restarting the app. Login reports RES_TLS, refreshed before each re-login. The reconnect flag is consumed before the drop check and cleared before reconnecting so a switch racing a disconnect cannot cause an extra reconnect/login cycle. Cross-compile OpenSSL 3.5.0 per ABI with build_openssl_android.sh (NDK clang + MSYS2 perl/make), integrated into build_android_libs.ps1 (-OpenSslOnly). Static libs and per-ABI headers are tracked like the existing libzstd/libsign prebuilts; --exclude-libs keeps OpenSSL symbols private to libyama.so, isolated from the Java-layer Conscrypt. Co-Authored-By: Qoder <noreply@qoder.com>
236 lines
13 KiB
C++
236 lines
13 KiB
C++
// TlsChannel.h — 客户端单向 TLS 会话封装(Windows: Schannel;Linux: OpenSSL)
|
||
//
|
||
// 用途:为 YAMA 客户端(被控端)提供「按需开启」的传输层加密。当信任锚证书存在时,
|
||
// 所有出站 TCP 连接在应用协议首包前先完成 TLS 握手;握手失败一律断开
|
||
// (fail-closed,不回退明文)。
|
||
//
|
||
// 选型:
|
||
// - 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 释放上下文)与
|
||
// Send/Recv 对上下文的使用由 m_ctxMtx 互斥,避免重连线程释放上下文时与使用线程产生
|
||
// use-after-free。本对象作为 IOCPClient 的值成员存在,析构时释放上下文。
|
||
//
|
||
// 平台范围:_WIN32(Schannel)、Linux 与 Android(OpenSSL)有实现;macOS 不含任何内容,
|
||
// 客户端维持明文。这些平台都通过 YAMA_TLS_CHANNEL 宏告知调用方「本平台有 TLS 通道」。
|
||
// Android 复用 Linux 的 OpenSSL 实现(TlsChannelLinux.cpp),唯一差异是信任锚目录改为
|
||
// App 私有 filesDir(由 TlsSetAnchorDir 注入),语义(单向 TLS1.2 钉扎、fail-closed、
|
||
// 热重载)与 Linux 完全一致。
|
||
#pragma once
|
||
|
||
#if defined(_WIN32)
|
||
|
||
#define YAMA_TLS_CHANNEL 1
|
||
|
||
#include <WinSock2.h>
|
||
|
||
#ifndef SECURITY_WIN32
|
||
#define SECURITY_WIN32 1
|
||
#endif
|
||
#include <security.h>
|
||
#include <schannel.h>
|
||
|
||
#include <mutex>
|
||
#include <string>
|
||
#include <vector>
|
||
|
||
// 进程级 TLS 开关(不看目标地址,等价于「允许使用内嵌锚」那一套状态):首次调用时加载
|
||
// 信任锚(注册表或文件),返回是否启用。线程安全。
|
||
// Windows 版同样是「可热切换」的:TlsReload() 之后本函数立刻反映新状态(不是 call_once)。
|
||
// 需要「这条连接会不会走 TLS」时用下面的 TlsEnabledFor(host)——分享/并行实例与主连接的
|
||
// 答案可能不同(内嵌锚只对生成时那台主控有效)。
|
||
bool TlsEnabled();
|
||
|
||
// 信任锚已配置但加载失败(损坏/格式错误)时为 true:表示管理员已「颁发」证书,
|
||
// 客户端必须拒绝连接(fail-closed),不得静默回退明文。线程安全、幂等。
|
||
bool TlsLoadError();
|
||
|
||
// 按「本连接要连到哪里」给出 TLS 开关与 fail-closed 状态。host 可以是域名、IP,或分号
|
||
// 分隔的多地址(与 CONNECT_ADDRESS 的写法一致);为空表示不限定目标(按进程级开关处理)。
|
||
//
|
||
// 为什么要按连接判定:分享实例、并行的多主控实例都是**同一个进程里的线程**
|
||
// (ClientDll.cpp 的 __CreateThread(0,0,StartClientApp,...)),一个进程级布尔量既表达不了
|
||
// 「主连接用内嵌锚、分享连接不用」,也不该由先发起连接的那个线程决定(状态首次使用时
|
||
// 缓存,谁先连谁说了算)。内嵌锚只在「连的正是生成时那台主控」时生效,判定在 TLS 层内部
|
||
// 完成:地址字符串直接相等,或两侧解析出的 IP 相交。
|
||
//
|
||
// connectHost:本连接实际连到的地址(IOCPClient 的 m_sCurIP,通常是解析后的 IP)。
|
||
// configured:配置里的原始写法(可能含分号分隔的多地址/域名),可为空。域名对域名
|
||
// 靠它做快路径,不必依赖两次 DNS 查询得到同一个答案。
|
||
bool TlsEnabledFor(const std::string& connectHost, const std::string& configured);
|
||
bool TlsLoadErrorFor(const std::string& connectHost, const std::string& configured);
|
||
|
||
// 按当前信任锚位置(注册表 settings\tls_cert → settings.ini → exe 同目录 yama-ca.pem)
|
||
// 重建 TLS 上下文并更新开关,让随后建立的新连接立刻走新传输方式(已建立的连接不受
|
||
// 影响)。信任锚无效时不做任何改动、返回 false 并给出原因——一次坏下发不该把正在工作
|
||
// 的客户端打死(下次启动仍 fail-closed)。线程安全:与 TlsEnabled/TlsLoadError/握手
|
||
// 的证书校验互斥。
|
||
bool TlsReload(std::string& err);
|
||
|
||
class TlsChannel
|
||
{
|
||
public:
|
||
TlsChannel() {}
|
||
~TlsChannel() { CloseHandles(); }
|
||
|
||
// 持 Schannel 句柄,禁止拷贝/赋值(避免句柄被二次释放)。
|
||
TlsChannel(const TlsChannel&) = delete;
|
||
TlsChannel& operator=(const TlsChannel&) = delete;
|
||
|
||
// 在已连通的 socket 上完成 TLS 客户端握手并校验服务端证书链。失败返回 false,
|
||
// 调用方必须关闭 socket(fail-closed)。可重复调用(重连时复用同一对象)。
|
||
// sni 非空且为域名时作为 SNI 发送,让反代(nginx)按域名分流到正确的 server 块;
|
||
// 证书校验仍只钉信任锚、不校主机名,与直接连主控端口时完全一致。
|
||
// host/configured:同 TlsEnabledFor,决定证书校验用哪一套信任锚——目标不是生成时
|
||
// 那台主控时不能拿内嵌锚去校验,否则必然失败且无法自愈。
|
||
bool Handshake(SOCKET sock, const char* sni, const std::string& host,
|
||
const std::string& configured);
|
||
|
||
// 解密读取:返回 >0 的明文字节数;0 表示对端正常关闭;SOCKET_ERROR(-1) 出错。
|
||
int Recv(SOCKET sock, char* buf, int len);
|
||
|
||
// 加密发送 len 字节:成功返回已完整发送的明文字节数(== len);失败返回已发送的
|
||
// 前缀字节数(>0)或 SOCKET_ERROR(一个字节都没发出去时)。
|
||
int Send(SOCKET sock, const char* buf, int len);
|
||
|
||
// 是否有待交付的数据:已解密明文(m_pending)或已缓冲但尚未解密的 TLS 记录(m_raw)。
|
||
// 供接收线程在 select 前优先消费——select 只看底层 socket,看不到 Schannel 缓冲的
|
||
// m_raw(握手时随 Finished 收下的首条应用数据、或一次 recv 到多条记录后的剩余),
|
||
// 若这里不把 m_raw 也算作「有数据」,这些字节会被 select 卡住。
|
||
bool HasPending() const { return !m_pending.empty() || !m_raw.empty(); }
|
||
|
||
// 握手是否已完成(Send/Recv 可用)。诊断用:区分「本连接已走 TLS」与「裸连接」。
|
||
bool IsReady() const { return m_ready; }
|
||
|
||
// 本连接校验服务端证书时用的是不是内嵌锚。登录上报 CLIENT_CAP_EMBEDDED_ANCHOR 用:
|
||
// 只有这种客户端会在服务端关掉 TLS 后失联,操作员据此决定是否先下发取消。
|
||
bool AnchorEmbedded() const { return m_anchorEmbedded; }
|
||
|
||
private:
|
||
void CloseHandles();
|
||
bool SendAll(SOCKET sock, const void* data, int len);
|
||
bool VerifyServerCert();
|
||
|
||
CredHandle m_cred = {};
|
||
CtxtHandle m_ctx = {};
|
||
bool m_credValid = false; // m_cred 已分配,需 FreeCredentialsHandle
|
||
bool m_ctxValid = false; // m_ctx 已分配,需 DeleteSecurityContext
|
||
bool m_ready = false; // 握手完成,Send/Recv 可用
|
||
bool m_anchorEmbedded = false; // 本次握手用的是内嵌锚(见 AnchorEmbedded)
|
||
int m_stateIdx = 1; // 本次握手用的信任锚状态(1=允许内嵌锚;0=不用)
|
||
|
||
SecPkgContext_StreamSizes m_sizes = {};
|
||
|
||
// 保护上下文生命周期:重连线程的 Handshake/CloseHandles(释放 m_ctx)与工作线程的
|
||
// Recv(DecryptMessage)、发送线程的 Send(EncryptMessage)互斥,避免 use-after-free。
|
||
// recursive 是因为 Handshake 内部会再调 CloseHandles。
|
||
std::recursive_mutex m_ctxMtx;
|
||
|
||
std::vector<BYTE> m_raw; // 尚未解密 / 未消费完的 TLS 记录原始字节
|
||
std::vector<BYTE> m_pending; // 已解密、未交付给应用层的明文
|
||
};
|
||
|
||
#elif defined(__linux__) // 含 Android:__ANDROID__ 同时定义 __linux__
|
||
|
||
#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();
|
||
|
||
// Windows 版按目标地址区分「用不用内嵌锚」。Linux / Android 客户端没有内嵌锚概念(生成器
|
||
// 只往 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
|
||
// 时退回程序目录);
|
||
// Android:App 私有 filesDir/yama-ca.pem(目录由 TlsSetAnchorDir 注入)。
|
||
// 落盘后用 TlsReload() 立即生效(Windows 客户端在 COMMAND_TLS_ENABLE 里调用同一个
|
||
// TlsReload(),各平台行为一致)。
|
||
bool TlsTrustAnchorSave(const std::string& pem, std::string& err);
|
||
|
||
// 服务端撤销信任锚(COMMAND_TLS_DISABLE):删除上述配置文件(含程序目录同名文件)。
|
||
// 返回是否删掉了至少一个文件;之后同样用 TlsReload() 立即生效。
|
||
bool TlsTrustAnchorRemove(std::string& err);
|
||
|
||
#ifdef __ANDROID__
|
||
// Android:注入信任锚目录(App 私有 context.filesDir,无需存储权限、跨重启持久)。
|
||
// 必须在首次 TlsEnabled()/握手前调用一次(nativeInit 里)。Linux 用 XDG_CONFIG_HOME/HOME
|
||
// 定位目录,不需要此函数。设一次后不再变更,故与 TLS 状态锁无竞争。
|
||
void TlsSetAnchorDir(const std::string& dir);
|
||
#endif
|
||
|
||
// 按当前信任锚文件重建 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)。可重复调用(重连时复用同一对象)。
|
||
// sni 非空且为域名时作为 SNI 发送(反代按域名分流);证书校验仍只钉信任锚。
|
||
// 后两个参数与 Windows 版同签名,本平台无内嵌锚,忽略。
|
||
bool Handshake(int sock, const char* sni, const std::string& host,
|
||
const std::string& configured);
|
||
|
||
// 解密读取:返回 >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; }
|
||
|
||
// Linux / Android 客户端没有内嵌锚(见上),恒为 false,与 Windows 版签名保持一致。
|
||
bool AnchorEmbedded() const { return false; }
|
||
|
||
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)
|