Exposed ports see a constant stream of scanners and HTTP probes. Every TLS handshake attempt logged an ioctlsocket(FIONBIO=0) failure, but WSAEINVAL is the documented result once WSAEventSelect owns the listening socket and the code already falls back to select; that line alone accounted for 6678 of the 8970 "handshake" lines in a four-day log. It is now logged only for other error codes. A failed handshake used to print three or four lines (recv EOF, AcceptSecurityContext, final status, failed-for-IP) with no per-peer dedup, and WS upgrade failures printed once per HTTP probe. ServerTlsSession now records a human-readable reason (Schannel status name for ASC failures) instead of logging per connection; IOCPServer prints one line per peer per hour with the reason and a suppressed count, for both TLS and WS. Peer close_notify is a normal shutdown and is no longer logged; MCP TLS failures now carry the same reason. Failure details are copied before the context's I/O reference is released, so the log path cannot touch a context that another thread may recycle. No handshake, crypto or connection behaviour changes. Verified with a Debug x64 build and a live probe run: six failed connections to the device port produced exactly one TLS and one WS line, with no ioctlsocket lines. Co-Authored-By: deepseek-flash
135 lines
7.2 KiB
C++
135 lines
7.2 KiB
C++
// ServerTlsSession.h — MFC 服务端单向 TLS(Schannel 入站)会话封装
|
||
//
|
||
// 与客户端 TlsChannel 对称:客户端走 InitializeSecurityContext(出站),本类走
|
||
// AcceptSecurityContext(入站)。单向 TLS:不请求/校验客户端证书,客户端身份仍由
|
||
// 隧道内登录(V1 PwdHmac / V2 ECDSA)承担。
|
||
//
|
||
// 分层:
|
||
// ServerTlsIdentity —— 进程级「服务端身份」(证书 + 私钥 → 入站凭据)。可重入加载
|
||
// (Load 禁止用 call_once,供未来 UI/指令热切换),本轮启动时加载一次。
|
||
// ServerTlsSession —— 每条连接一个,持有握手/加解密所需的 Schannel 上下文与缓冲,
|
||
// 随 CONTEXT_OBJECT 池化复用而重建。
|
||
//
|
||
// 线程模型:Handshake 在专用握手线程上阻塞执行(方案 A);握手完成后,Decrypt 由
|
||
// IOCP 工作线程调用(每连接同一时刻只有一个未决 WSARecv,天然串行)、Encrypt 在
|
||
// SendLock 内调用。Schannel 上下文非线程安全,故 Encrypt/Decrypt 内部以 m_mtx 互斥。
|
||
//
|
||
// 选型:Schannel(Windows 原生 SSPI),secur32.lib / crypt32.lib / ncrypt.lib 系统库。
|
||
// 证书/私钥为 PEM(与 Go 服务端 YAMA_TLS_CERT/KEY 同构,可共用同一对密钥);私钥
|
||
// 须为 PKCS#8(-----BEGIN PRIVATE KEY-----),见 ServerTlsSession.cpp 的加载实现。
|
||
#pragma once
|
||
|
||
#include <WinSock2.h>
|
||
|
||
#ifndef SECURITY_WIN32
|
||
#define SECURITY_WIN32 1
|
||
#endif
|
||
#include <security.h>
|
||
#include <schannel.h>
|
||
|
||
#include <mutex>
|
||
#include <string>
|
||
#include <vector>
|
||
|
||
class config; // common/iniFile.h(仅需引用,避免把 ini 头拖进 Server.h 的 include 图)
|
||
|
||
// ---- 进程级服务端身份(证书 + 私钥),可重入加载(禁止 call_once,供未来热切换)----
|
||
class ServerTlsIdentity
|
||
{
|
||
public:
|
||
// 从 cfg(THIS_CFG)读 [tls] 节:Enabled(缺省启用)/ UseBuiltIn / CertPath / KeyPath,
|
||
// 并加载身份。证书来源两种:内置证书(服务端首次启用时自动生成,见 BuiltinTlsCert.h)
|
||
// 或用户指定的证书/私钥文件。
|
||
// 返回 true 表示「配置已生效」(开关关、或开关开且身份加载成功);开关开但加载
|
||
// 失败时返回 false 且 IsLoadError()==true,服务端须对 TLS ClientHello fail-closed。
|
||
static bool Load(config& cfg);
|
||
|
||
static bool IsEnabled(); // [tls] Enabled != 0(缺省为启用)
|
||
static bool IsReady(); // 开关开 && 身份加载成功(有可用入站凭据)
|
||
static bool IsLoadError(); // 开关开 && 身份加载失败(fail-closed)
|
||
static bool IsBuiltin(); // 就绪且当前身份来自内置证书(状态栏「TLS: 内置」)
|
||
|
||
// 入站凭据(AcquireCredentialsHandle 产出)。返回拷贝;句柄值本身可安全拷贝。
|
||
static CredHandle Cred();
|
||
|
||
// 当前身份的信任锚 PEM(自定义证书时为证书文件全文,fullchain 一并带上;
|
||
// 内置证书时为自签证书的 PEM)。用于「启用 TLS / 切换到 WSS」指令下发给客户端。
|
||
static bool AnchorPem(std::string& out);
|
||
|
||
private:
|
||
static void FreeIdentity();
|
||
static bool LoadIdentity(const std::string& certPath, const std::string& keyPath);
|
||
static bool LoadIdentityFromDer(const std::vector<BYTE>& certDer, const std::vector<BYTE>& keyDer);
|
||
};
|
||
|
||
// ---- 额外入站身份(MCP 等第二套证书)----
|
||
//
|
||
// 进程级身份 ServerTlsIdentity 只服务设备端口,证书由 [tls] 指定(通常是自签
|
||
// CN=localhost)。MCP 要暴露给公网客户端,必须用公共 CA 签发的证书,故需要第二份
|
||
// 身份。两者可并存:证书/私钥各自加载,持久化私钥用不同的键名(keyName)分开存放,
|
||
// 不会互相覆盖。调用方负责在停止时调用 ServerTlsFreeIdentity。
|
||
struct ServerTlsExtraIdentity
|
||
{
|
||
CredHandle cred = {}; // AcquireCredentialsHandle 产出的入站凭据
|
||
PCCERT_CONTEXT cert = NULL; // 凭据按名引用的证书上下文
|
||
ULONG_PTR key = 0; // NCrypt 持久化私钥句柄(NCRYPT_KEY_HANDLE)
|
||
};
|
||
|
||
// 从 PEM(证书链 + PKCS#8 私钥)构造一份独立入站身份。keyName 为 CNG 持久化键名基名,
|
||
// 须与其它身份不同(例如 L"YamaServerTlsKey" / L"YamaMcpTlsKey");实际键名还会拼上
|
||
// 证书指纹,因此换证书不会与同用户的另一个实例撞名。
|
||
bool ServerTlsLoadIdentityFromPem(const std::string& certPath, const std::string& keyPath,
|
||
const wchar_t* keyName, ServerTlsExtraIdentity& out);
|
||
|
||
// 释放 ServerTlsLoadIdentityFromPem 构造的身份(先凭据、再证书、最后删除持久化私钥)。
|
||
void ServerTlsFreeIdentity(ServerTlsExtraIdentity& id);
|
||
|
||
// ---- 单连接服务端 TLS 会话(握手 + 加解密)----
|
||
class ServerTlsSession
|
||
{
|
||
public:
|
||
ServerTlsSession() {}
|
||
~ServerTlsSession() { CloseHandles(); }
|
||
|
||
ServerTlsSession(const ServerTlsSession&) = delete;
|
||
ServerTlsSession& operator=(const ServerTlsSession&) = delete;
|
||
|
||
// 阻塞式服务端握手(方案 A:专用握手线程上调用)。initial/initialLen 是嗅探阶段已
|
||
// 收到的 ClientHello 字节(可能只是分片;内部按 SEC_E_INCOMPLETE_MESSAGE 续收补齐)。
|
||
// 成功返回 true,失败 false(调用方关闭连接,fail-closed)。
|
||
bool Handshake(SOCKET sock, const BYTE* initial, int initialLen);
|
||
|
||
// 同上,但使用调用方提供的入站凭据(MCP TLS 前端用独立的第二份身份,
|
||
// 见 ServerTlsLoadIdentityFromPem)。
|
||
bool HandshakeWithCred(SOCKET sock, const BYTE* initial, int initialLen, CredHandle cred);
|
||
|
||
// 解密:把本次 WSARecv 收到的密文 cipher[0..len] 喂入,把能解出的明文追加到 plain。
|
||
// len == 0 表示只解出会话里已缓存的密文(握手结束后必须先取一次,否则紧随 Finished
|
||
// 到达的首条应用数据会一直躺着,直到客户端再发一包)。
|
||
// 返回 0 = 成功(可能无明文);-1 = 错误 / 对端 close_notify(调用方关闭连接)。
|
||
int Decrypt(const BYTE* cipher, int len, std::vector<BYTE>& plain);
|
||
|
||
// 加密:把明文 plain[0..len] 加密成完整 TLS 记录,追加到 wire。
|
||
// 返回加密的明文字节数(== len);-1 = 错误。
|
||
int Encrypt(const BYTE* plain, int len, std::vector<BYTE>& wire);
|
||
|
||
bool Ready() const { return m_ready; }
|
||
|
||
// 握手失败原因(人类可读;未失败时为空)。由调用方在 Handshake* 返回 false 后输出
|
||
// 一行汇总日志——会话内部不再逐条打印,避免公网扫描器/半截握手刷屏。
|
||
const std::string& LastError() const { return m_lastError; }
|
||
|
||
private:
|
||
void CloseHandles();
|
||
bool SendAll(SOCKET sock, const void* data, int len);
|
||
|
||
std::mutex m_mtx; // 序列化对 m_ctx 的 Encrypt/Decrypt(Schannel 非线程安全)
|
||
CtxtHandle m_ctx = {};
|
||
bool m_ctxValid = false;
|
||
bool m_ready = false;
|
||
SecPkgContext_StreamSizes m_sizes = {};
|
||
std::vector<BYTE> m_raw; // 尚未解密 / 未消费完的 TLS 记录原始字节
|
||
SECURITY_STATUS m_lastStatus = SEC_E_OK;
|
||
std::string m_lastError; // 握手失败原因,供调用方汇总输出
|
||
};
|