Files
SimpleRemoter/client/TlsChannel.h
T
6bfa4294cc Feature: Switch a Linux client's transport TLS at runtime
The server's TLS menu already wrote the trust anchor into the Windows
client's registry and expected a restart. The Linux client grew the same
command handling (166/167) but, like Windows, only read the anchor once at
startup, so enabling or disabling TLS still meant restarting it. Both
handlers now take effect immediately.

TlsChannelLinux.cpp no longer initialises through std::call_once. The
process-level state (context, enabled, load error) lives behind a mutex and
TlsReload() rebuilds it from whatever anchor file is on disk, so
TlsEnabled() reflects the new transport as soon as the anchor is written or
removed. In-flight sessions survive the swap because SSL_new increments the
SSL_CTX reference count; the unit test pins that down by keeping an
established TLS connection open across a reload that frees the old context.
A reload that hits a bad anchor keeps the previous state and only logs: one
bad push should not brick a working client, and the next start is still
fail-closed. The pushed PEM is parsed before it is written for the same
reason -- a corrupt anchor on disk would lock the client out of the server
with no way to correct it remotely.

Only a real transport flip (plaintext <-> TLS) asks for a reconnect. An
anchor swap alone, as in a certificate rotation, leaves the current session
alone and applies to the next connection. The receive thread never closes
the socket itself; it sets g_needReconnect and the main heartbeat loop
disconnects so the outer reconnect loop can re-handshake, matching how the
heartbeat timeout path already works.

IOCPClient now latches the transport per connection (m_useTls) at handshake
time instead of consulting TlsEnabled() on every send and receive. Without
the latch, the second or so between the reload and the reconnect would push
plaintext into an established TLS session, or the reverse, producing
protocol errors for no reason.

RES_TLS (szReserved[19]) is refreshed right before each login, including
the resend after a group change, so the TLS column on the server flips with
the transport instead of showing the value from process start.

The confirmation dialogs now say what each platform does, with translations
in en_US, zh_TW and de_DE; the keys carry the literal \n escape the INI
parser understands.

Ending a sub-connection is not an error. OpenSSL 3 classifies a peer that
closes without close_notify as an unexpected-EOF protocol error, so every
terminal or file transfer session logged an SSL_read failure on the real
servers even though Recv promises 0 for a plain close and neither side sends
close_notify. SSL_OP_IGNORE_UNEXPECTED_EOF restores the intended semantics.

Verified with the reload unit test (RELOAD-OK, covering the in-flight
connection across a context swap, garbage payload rejection and a broken
anchor keeping TLS alive), an abrupt-close test (recv now returns 0 instead
of SOCKET_ERROR) and end to end against a protocol-faithful fake server that
signs MasterSettings with libsign: plaintext login, 166, TLS reconnect with
RES_TLS=1, 167, plaintext reconnect with RES_TLS=0. The Linux client, the
Debug Windows client and the Debug MFC server all build.

The cost is inherent to taking effect immediately: a remote session in
progress is dropped when the transport changes, and the MFC server briefly
shows the client as a duplicate login until the old connection is reaped
and the standby entry is promoted.

Co-Authored-By: deepseek-flash
Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-10-28 14:15:40 +01:00

175 lines
8.5 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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 与 Linux(非 Android)有实现;macOS / Android 不含任何内容,客户端
// 维持明文(TLS 接入按设计文档延后)。两平台都通过 YAMA_TLS_CHANNEL 宏告知调用方
// 「本平台有 TLS 通道」。
#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 <vector>
// 进程级 TLS 开关:首次调用时加载信任锚(注册表或文件),返回是否启用。线程安全、幂等。
bool TlsEnabled();
// 信任锚已配置但加载失败(损坏/格式错误)时为 true:表示管理员已「颁发」证书,
// 客户端必须拒绝连接(fail-closed),不得静默回退明文。线程安全、幂等。
bool TlsLoadError();
class TlsChannel
{
public:
TlsChannel() {}
~TlsChannel() { CloseHandles(); }
// 持 Schannel 句柄,禁止拷贝/赋值(避免句柄被二次释放)。
TlsChannel(const TlsChannel&) = delete;
TlsChannel& operator=(const TlsChannel&) = delete;
// 在已连通的 socket 上完成 TLS 客户端握手并校验服务端证书链。失败返回 false,
// 调用方必须关闭 socket(fail-closed)。可重复调用(重连时复用同一对象)。
bool Handshake(SOCKET sock);
// 解密读取:返回 >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; }
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 可用
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__) && !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__