When the server has TLS enabled, the builder can now bake its certificate into the client it produces, so a distributed client speaks TLS on its very first connection instead of waiting for the anchor to be pushed after a plaintext login. The dialog gets a checkbox (IDC_CHECK_TLS_ANCHOR) that is only enabled for payloads and protocols where an embedded anchor makes sense; the choice is remembered even when the control flips to disabled and back, so switching protocols cannot silently undo a deliberate opt-out. Every label variant stays short enough to fit the 196 DLU field, including the German ones. A template that predates the anchor block no longer aborts generation: it warns, clears the checkbox and produces a plain client, so a master upgraded without rebuilding the ghost/ServerDll resources does not block every build. The certificate lands in a fixed 4 KiB block (magic, version, length, FNV-1a hash, master address, PEM) carved out of the payload at build time. The client reads its trust anchor from four sources in order: the tls_disabled marker, the certificate the server pushed into the registry, a PEM file next to the executable, and finally the embedded block. The embedded block only applies to a connection whose target matches the master recorded at generation time, compared as an address set: an exact string match when only one address is configured, or an intersection of resolved IPv4 addresses otherwise. A transferred, shared or parallel instance falls back to the old plaintext first-connect path instead of pinning itself to a certificate it can never verify. That decision is made per connection, not per process: shared and parallel instances are threads inside a single client process, so a process-wide flag let whichever instance connected first decide for all of them, and the first load of the TLS state cached that answer for good. The TLS layer now keeps two cached states (embedded anchor allowed, and not allowed), picks one per handshake, and reports the anchor source of that handshake for the login capability bit. Matching by resolved address also keeps parallel mode working, where the connection goes to the single IP the domain pool selected while the configured master is a domain or a list. Server side, generated and updated payloads get the block written in place; the client reports the capability bit on login so the console can tell which hosts are already TLS-only on first connect. Loading the anchor decodes every PEM block in the chain rather than just the leaf, and an anchor that exists but fails to load keeps the old fail-closed behaviour. A pushed anchor only reconnects when the transport of the live connection actually changes, judged against that connection's own target rather than the process-wide switch. This was verified end to end against a freshly generated client with an empty registry: the first connection was a TLS 1.2 ClientHello 0.2 s after start, and a four-certificate fullchain loaded all four blocks. Re-verified after the per-connection rework with the anchor block patched into a debug client: with a matching master the first bytes are a ClientHello, with a foreign master the client logs the skip and sends plaintext, and a domain master resolves to the IP it connects to and still matches. A master domain that no longer resolves falls back to plaintext within a second and is not looked up again for a minute, instead of stalling every reconnect on a DNS timeout while holding the lock the certificate verification needs. Co-Authored-By: deepseek-flash
882 lines
37 KiB
C++
882 lines
37 KiB
C++
// TlsChannel.cpp — 见 TlsChannel.h 头注释。仅 _WIN32 编译。
|
||
#ifdef _WIN32
|
||
|
||
#include "stdafx.h"
|
||
#include "TlsChannel.h"
|
||
#include "EmbeddedTlsAnchor.h" // 生成客户端时写进镜像的信任锚块(ReadTrustAnchor 第四级)
|
||
|
||
#include "common/iniFile.h" // config(settings.ini 文件回退) + GetRegistryName/GetCurrentUserRegistryKey(注册表正文)
|
||
#include "domain_pool.h" // GetIPAddress:把内嵌锚的主控地址(可能是域名)解析成 IP
|
||
|
||
#include <wincrypt.h> // 证书/链引擎 API
|
||
#include <winreg.h> // RegOpenKeyExA / RegQueryValueExA
|
||
#include <ctype.h> // tolower
|
||
#include <io.h> // _access
|
||
#include <fstream> // std::ifstream
|
||
#include <iterator> // std::istreambuf_iterator
|
||
#include <string>
|
||
#include <map> // std::map(域名解析缓存)
|
||
#include <mutex> // std::mutex
|
||
|
||
#pragma comment(lib, "secur32.lib")
|
||
#pragma comment(lib, "crypt32.lib")
|
||
|
||
namespace {
|
||
|
||
// 一套 TLS 状态:信任锚 store + 链引擎 + 开关。按「本连接是否允许使用内嵌锚」分两套:
|
||
// g_state[1]:允许(连的正是生成时那台主控)——绝大多数情况
|
||
// g_state[0]:不使用内嵌块(被转移/被分享/并行实例连的是别的主控)
|
||
// 为什么必须按连接分:分享实例与并行多主控实例是**同一个进程里的线程**
|
||
// (ClientDll.cpp 的 __CreateThread(0, 0, StartClientApp, ...)),一个进程级布尔量既
|
||
// 表达不了「主连接用锚、分享连接不用」,也不该由先发起连接的那个线程决定——状态是首次
|
||
// 使用时缓存的,谁先连谁说了算(设计文档 §3.6)。
|
||
struct TlsState {
|
||
bool loaded = false; // 已加载过至少一次(决定首次失败是否 fail-closed)
|
||
bool enabled = false; // TLS 会话可用:send/recv 走加密
|
||
bool error = false; // 证书存在但加载失败:拒绝连接(fail-closed)
|
||
bool anchorEmbedded = false; // 本套状态生效的锚来自内嵌块
|
||
std::string source; // 锚来源,仅用于日志
|
||
HCERTSTORE store = NULL;
|
||
HCERTCHAINENGINE engine = NULL; // 只信任 store 的链引擎(严格钉扎)
|
||
};
|
||
|
||
// 所有读写都在 g_tlsMtx 下;证书校验(VerifyServerCert)在校验期间持同一把锁,因此
|
||
// 重建时可以安全地释放旧的 store/engine——不会再有线程正拿着它们用。
|
||
std::mutex g_tlsMtx;
|
||
TlsState g_state[2];
|
||
|
||
// 地址匹配用的锁,与 g_tlsMtx **分开**:匹配过程要解析域名,而 gethostbyname 可能卡上
|
||
// 几秒到几十秒(DNS 不通时),绝不能压着证书校验那把锁。只在读写下面两个缓存与去重键时
|
||
// 持锁,真正解析地址在锁外。
|
||
std::mutex g_matchMtx;
|
||
|
||
// 地址解析缓存:内嵌锚的 master 可能写成域名,而运行时(并行实例)连的是 DomainPool
|
||
// 解析出的 IP,必须比 IP 才知道是不是同一台主控。只在 g_matchMtx 下访问。
|
||
std::map<std::string, std::string> g_dnsCache;
|
||
|
||
// 解析失败的负缓存(条目 → 失败时刻,GetTickCount64)。域名换过/过期而客户端还写着旧
|
||
// 域名时,若失败不缓存,**每次连接**都要白等一轮 DNS 超时(连接莫名变慢,且很难归因)。
|
||
// 缓 60 秒:短到 DNS 恢复后很快跟上,长到不会把每个重连都拖一遍。只在 g_matchMtx 下访问。
|
||
const ULONGLONG kDnsFailTtlMs = 60 * 1000;
|
||
std::map<std::string, ULONGLONG> g_dnsFailAt;
|
||
|
||
// 「内嵌锚不适用」日志去重(重连循环每几秒一轮,不能每次刷屏)。只在 g_matchMtx 下访问。
|
||
std::string g_lastSkipLog;
|
||
|
||
// 解析信任锚证书路径:优先 settings.ini 的 [settings] tls_cert,其次可执行文件同目录
|
||
// yama-ca.pem。
|
||
std::string ResolveCertPath()
|
||
{
|
||
std::string certPath;
|
||
{
|
||
config cfg;
|
||
certPath = cfg.GetStr("settings", "tls_cert", "");
|
||
}
|
||
if (certPath.empty()) {
|
||
char path[MAX_PATH];
|
||
if (!GetModuleFileNameA(NULL, path, sizeof(path)))
|
||
return std::string(); // 拿不到 exe 路径,视为未配置
|
||
char* p = path + strlen(path);
|
||
while (p > path && *p != '\\') --p;
|
||
strcpy(p + 1, "yama-ca.pem");
|
||
certPath = path;
|
||
}
|
||
return certPath;
|
||
}
|
||
|
||
// 读取注册表 REG_SZ(动态扩容,可区分「值不存在」与「值为空」):实现已并入
|
||
// common/iniFile.h 的 ReadRegistrySz——服务端内置 TLS 证书同样要读 1~2KB 的长值,
|
||
// 放在公共头里两端共用,避免各写一份。
|
||
|
||
// 取信任锚 PEM 正文。四级来源,优先级从高到低:
|
||
// 1. 抑制标记 settings\tls_disabled == "1" → 未配置(强制明文)
|
||
// 2. 注册表 settings\tls_cert(服务端在线下发,REG_SZ 直接存 PEM 正文)
|
||
// 3. settings.ini [settings] tls_cert 路径 / exe 同目录 yama-ca.pem(手工投放)
|
||
// 4. 内嵌锚块(生成客户端时写进镜像,出厂默认;需主控地址匹配,见 §3.6)
|
||
// 返回 true 表示已配置(pem 可能为空:值/文件存在但内容为空,由 LoadTrustAnchor 判为
|
||
// fail-closed);false 表示完全未配置(走明文)。source 描述来源,仅用于日志。
|
||
// allowEmbedded:是否允许落到第 4 级内嵌块(按目标地址判定,见 EmbeddedAnchorAppliesTo)。
|
||
// quiet:静默加载(第二套状态试建时用),失败原因仍经 err 返回。
|
||
bool ReadTrustAnchor(std::string& pem, std::string& source, bool allowEmbedded, bool quiet)
|
||
{
|
||
std::string regSubKey = GetRegistryName() + "\\settings";
|
||
|
||
// 1) 「取消 TLS」抑制标记。必须压过内嵌锚:COMMAND_TLS_DISABLE 只删 tls_cert 时,
|
||
// 客户端会回落到内嵌锚继续发 ClientHello,而服务端此时按明文处理 → StartTlsHandshake
|
||
// fail-closed 关闭 → 客户端再也连不上、也收不到任何后续指令(设计文档 §3.5)。
|
||
// 抑制标记压过**所有**信任锚来源,包括管理员手工投放的 PEM:这是操作员明确的
|
||
// 「本机不加密」意图,热切换失败时它必须能兜住,否则客户端会回落到别的锚继续
|
||
// 发 ClientHello,而服务端此时按明文处理(§3.5)。日志里点明「配置的证书也被忽略」,
|
||
// 免得排查时误以为 PEM 没生效是加载失败。
|
||
std::string disabled;
|
||
if (ReadRegistrySz(GetCurrentUserRegistryKey(), regSubKey, "tls_disabled", disabled) && disabled == "1") {
|
||
source = "registry " + regSubKey + "\\tls_disabled";
|
||
if (!quiet)
|
||
Mprintf("[TLS] disabled by server (tls_disabled=1), ignoring any configured "
|
||
"certificate; plaintext mode\n");
|
||
return false;
|
||
}
|
||
|
||
// 2) 注册表正文。值存在(即便为空)即视为「已配置」,交由 LoadTrustAnchor 对空/损坏
|
||
// 内容判 fail-closed,与「空文件 → fail-closed」语义一致,避免空值被静默当成未配置。
|
||
std::string regVal;
|
||
if (ReadRegistrySz(GetCurrentUserRegistryKey(), regSubKey, "tls_cert", regVal)) {
|
||
pem = regVal;
|
||
source = "registry " + regSubKey + "\\tls_cert";
|
||
return true;
|
||
}
|
||
|
||
// 3) 文件回退:settings.ini [settings] tls_cert 路径 → exe 同目录 yama-ca.pem
|
||
std::string certPath = ResolveCertPath();
|
||
if (!certPath.empty() && _access(certPath.c_str(), 0) == 0) {
|
||
std::ifstream f(certPath.c_str(), std::ios::binary);
|
||
if (!f) {
|
||
if (!quiet)
|
||
Mprintf("[TLS] cannot open %s\n", certPath.c_str());
|
||
} else {
|
||
pem.assign((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
|
||
source = certPath;
|
||
return true;
|
||
}
|
||
}
|
||
|
||
// 4) 内嵌锚块(出厂默认)。allowEmbedded 为假表示本目标不是生成时那台主控
|
||
// (被转移/被分享/并行实例):拿原主控的证书去校验新主控必然失败,fail-closed 之后
|
||
// 又收不到新锚,只能重新生成客户端(§3.6)。
|
||
if (allowEmbedded) {
|
||
EmbeddedTlsAnchor anchor;
|
||
GetEmbeddedAnchor(anchor);
|
||
if (anchor.length > 0) {
|
||
if (!IsAnchorBlockValid(anchor)) {
|
||
// 损坏按「未配置」处理而不是 fail-closed:坏的可能是构建产物本身,
|
||
// fail-closed 会让整批客户端彻底不可用;明文至少还能连上并接受下发(§6.4)。
|
||
if (!quiet)
|
||
Mprintf("[TLS] embedded anchor corrupt (length=%u), ignored\n", (unsigned)anchor.length);
|
||
} else {
|
||
pem.assign(anchor.pem, anchor.length);
|
||
source = "embedded";
|
||
return true;
|
||
}
|
||
}
|
||
}
|
||
|
||
return false; // 无证书 → 明文
|
||
}
|
||
|
||
// 去掉首尾空白并转小写:域名大小写不敏感,配置里出现空格是常事。
|
||
std::string NormalizeEntry(const std::string& s)
|
||
{
|
||
size_t b = 0, e = s.size();
|
||
while (b < e && (s[b] == ' ' || s[b] == '\t')) ++b;
|
||
while (e > b && (s[e - 1] == ' ' || s[e - 1] == '\t')) --e;
|
||
std::string out(s, b, e - b);
|
||
for (size_t i = 0; i < out.size(); ++i)
|
||
out[i] = (char)tolower((unsigned char)out[i]);
|
||
return out;
|
||
}
|
||
|
||
// 按分号拆分多地址(与 CONNECT_ADDRESS / DomainPool 的写法一致),逐项规范化。
|
||
std::vector<std::string> SplitAddresses(const std::string& s)
|
||
{
|
||
std::vector<std::string> out;
|
||
size_t pos = 0;
|
||
for (;;) {
|
||
const size_t semi = s.find(';', pos);
|
||
std::string item = NormalizeEntry(s.substr(pos, semi == std::string::npos ? std::string::npos
|
||
: semi - pos));
|
||
if (!item.empty())
|
||
out.push_back(item);
|
||
if (semi == std::string::npos)
|
||
break;
|
||
pos = semi + 1;
|
||
}
|
||
return out;
|
||
}
|
||
|
||
bool IsIpv4Literal(const std::string& s)
|
||
{
|
||
return !s.empty() && inet_addr(s.c_str()) != INADDR_NONE;
|
||
}
|
||
|
||
// 把一个地址条目解析成 IPv4;本身是 IP 就直接返回。解析失败返回空串。
|
||
// 调用方**不得**持 g_tlsMtx:真正的解析在锁外做(见 g_matchMtx 的注释)。成功永久缓存,
|
||
// 失败按 kDnsFailTtlMs 负缓存。
|
||
std::string ResolveEntry(const std::string& entry)
|
||
{
|
||
if (IsIpv4Literal(entry))
|
||
return entry;
|
||
|
||
{
|
||
std::lock_guard<std::mutex> lk(g_matchMtx);
|
||
auto it = g_dnsCache.find(entry);
|
||
if (it != g_dnsCache.end() && !it->second.empty())
|
||
return it->second;
|
||
auto f = g_dnsFailAt.find(entry);
|
||
if (f != g_dnsFailAt.end() && GetTickCount64() - f->second < kDnsFailTtlMs)
|
||
return std::string(); // 刚失败过,别在热路径上再等一次超时
|
||
}
|
||
|
||
const std::string ip = GetIPAddress(entry.c_str()); // 锁外:可能阻塞数秒
|
||
const std::string v = IsIpv4Literal(ip) ? ip : std::string();
|
||
|
||
std::lock_guard<std::mutex> lk(g_matchMtx);
|
||
if (v.empty()) {
|
||
g_dnsFailAt[entry] = GetTickCount64();
|
||
} else {
|
||
g_dnsCache[entry] = v;
|
||
g_dnsFailAt.erase(entry);
|
||
}
|
||
return v;
|
||
}
|
||
|
||
// 内嵌锚是否适用于本次连接(不持 g_tlsMtx;内部只对缓存加 g_matchMtx,解析在锁外)。
|
||
//
|
||
// 判定分两层,任何一层命中即可:
|
||
// 1. 直接相等:配置里只写了一个地址,且与生成时的主控地址一字不差(域名对域名)。
|
||
// 必须保留这一层——生成端填域名、运行时按域名连接时,靠字符串就能定案,不必
|
||
// 依赖 DNS 的答案在两次查询之间保持一致。
|
||
// 2. IP 相交:两侧(可能是分号分隔的多地址、可能是域名)解析出的 IPv4 有交集。
|
||
// 并行实例连的是 DomainPool 解析后的单个 IP,生成端填的却是域名,只能靠这一层。
|
||
//
|
||
// host 为空表示调用方没给目标(进程级调用),按「允许」处理,与改造前的行为一致。
|
||
bool EmbeddedAnchorAppliesTo(const std::string& host, const std::string& configured)
|
||
{
|
||
EmbeddedTlsAnchor anchor;
|
||
GetEmbeddedAnchor(anchor);
|
||
if (anchor.length == 0 || !IsAnchorBlockValid(anchor))
|
||
return false; // 没有内嵌锚:用不用都是同一结果,不值得再比地址
|
||
|
||
if (host.empty())
|
||
return true;
|
||
|
||
const std::string builtFor(anchor.master, strnlen(anchor.master, sizeof(anchor.master)));
|
||
const std::vector<std::string> masters = SplitAddresses(builtFor);
|
||
const std::vector<std::string> targets = SplitAddresses(host);
|
||
|
||
bool match = false;
|
||
|
||
// 1) 配置里只写了一个地址:与主控地址直接比字符串。
|
||
const std::vector<std::string> configuredEntries = SplitAddresses(configured);
|
||
if (configuredEntries.size() == 1) {
|
||
for (size_t i = 0; i < masters.size() && !match; ++i)
|
||
match = (masters[i] == configuredEntries[0]);
|
||
}
|
||
|
||
// 2) 连接目标(IP)落在主控地址解析出的 IP 集合里。
|
||
for (size_t i = 0; i < targets.size() && !match; ++i) {
|
||
const std::string tip = ResolveEntry(targets[i]);
|
||
if (tip.empty())
|
||
continue;
|
||
for (size_t j = 0; j < masters.size() && !match; ++j)
|
||
match = (ResolveEntry(masters[j]) == tip);
|
||
}
|
||
|
||
if (!match) {
|
||
const std::string key = builtFor + "|" + host;
|
||
bool log = false;
|
||
{
|
||
std::lock_guard<std::mutex> lk(g_matchMtx);
|
||
if (g_lastSkipLog != key) { g_lastSkipLog = key; log = true; }
|
||
}
|
||
if (log) {
|
||
Mprintf("[TLS] embedded anchor skipped: connecting %s, built for %s\n",
|
||
host.c_str(), builtFor.c_str());
|
||
}
|
||
}
|
||
return match;
|
||
}
|
||
|
||
// 把一段 DER 加入信任锚存储;不是合法证书就静默跳过。返回是否加入成功。
|
||
static bool AddDerCert(const BYTE* der, DWORD cb, HCERTSTORE store)
|
||
{
|
||
if (!der || cb == 0)
|
||
return false;
|
||
PCCERT_CONTEXT cert = CertCreateCertificateContext(X509_ASN_ENCODING, der, cb);
|
||
if (!cert)
|
||
return false;
|
||
const bool ok = CertAddCertificateContextToStore(store, cert,
|
||
CERT_STORE_ADD_REPLACE_EXISTING, NULL) != FALSE;
|
||
CertFreeCertificateContext(cert);
|
||
return ok;
|
||
}
|
||
|
||
// 从 pem 的 pos 起取下一个 PEM 块(-----BEGIN … -----END 两行含在内),pos 前移到块后。
|
||
static bool NextPemBlock(const std::string& pem, size_t& pos, std::string& block)
|
||
{
|
||
const size_t begin = pem.find("-----BEGIN", pos);
|
||
if (begin == std::string::npos)
|
||
return false;
|
||
const size_t end = pem.find("-----END", begin);
|
||
if (end == std::string::npos) {
|
||
pos = pem.size(); // 只有 BEGIN 没有 END:残缺块,别再往后找
|
||
return false;
|
||
}
|
||
const size_t eol = pem.find('\n', end); // 一直取到 END 那一行结束(兼容 CRLF)
|
||
const size_t stop = (eol == std::string::npos) ? pem.size() : eol + 1;
|
||
block.assign(pem, begin, stop - begin);
|
||
pos = stop;
|
||
return true;
|
||
}
|
||
|
||
// 把 PEM 里的**所有**证书块解码并加入信任锚存储,返回加入的证书张数。
|
||
//
|
||
// 必须循环:内置自签证书只有一张,但用户自备的是 leaf-first fullchain(叶证书 + 中间
|
||
// CA)。只把叶证书放进独占根存储,CertGetCertificateChain 就建不出链 → 握手失败 →
|
||
// fail-closed。Linux 端 TlsChannelLinux.cpp::LoadAnchors 一直是循环读全部块的,这里补齐
|
||
// 同一语义(设计文档 §5 P1)。
|
||
//
|
||
// 不能用 CryptStringToBinaryA 的 pdwSkip 走多块:该参数是纯输出的——回报「转换前跳过了
|
||
// 多少字符」,调用方传进去的偏移一概不看,整串输入时永远是 0。曾按「回报下一块起点」用它
|
||
// 循环,结果下一轮就被 `next <= offset` 的防死循环判断挡下,一张证书都加不进去(内嵌锚
|
||
// 客户端首次连接直接 fail-closed,2026-11-01 实测)。因此这里自己按 BEGIN/END 切块。
|
||
static int DecodeAllCerts(const std::string& pem, DWORD flags, HCERTSTORE store,
|
||
const std::string& source, bool quiet)
|
||
{
|
||
int added = 0;
|
||
size_t pos = 0;
|
||
std::string block;
|
||
while (NextPemBlock(pem, pos, block)) {
|
||
DWORD derLen = 0;
|
||
if (!CryptStringToBinaryA(block.c_str(), (DWORD)block.size(), flags,
|
||
NULL, &derLen, NULL, NULL) || derLen == 0)
|
||
continue; // 这一块不是该 flags 认得的内容:跳过,后面的块还有机会
|
||
|
||
std::vector<BYTE> der(derLen);
|
||
DWORD cb = derLen;
|
||
if (!CryptStringToBinaryA(block.c_str(), (DWORD)block.size(), flags,
|
||
der.data(), &cb, NULL, NULL)) {
|
||
if (!quiet)
|
||
Mprintf("[TLS] failed to decode a certificate block in %s\n", source.c_str());
|
||
continue;
|
||
}
|
||
if (AddDerCert(der.data(), cb, store))
|
||
++added;
|
||
}
|
||
return added;
|
||
}
|
||
|
||
// 解码 PEM/DER 信任锚正文,并加入内存信任锚存储。
|
||
bool LoadTrustAnchor(const std::string& pem, const std::string& source, bool quiet,
|
||
HCERTSTORE* outStore)
|
||
{
|
||
if (pem.empty()) {
|
||
if (!quiet)
|
||
Mprintf("[TLS] empty certificate %s\n", source.c_str());
|
||
return false;
|
||
}
|
||
|
||
HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, X509_ASN_ENCODING,
|
||
0, CERT_STORE_CREATE_NEW_FLAG, NULL);
|
||
if (!store) {
|
||
if (!quiet)
|
||
Mprintf("[TLS] CertOpenStore failed\n");
|
||
return false;
|
||
}
|
||
|
||
// 先按标准 PEM(-----BEGIN CERTIFICATE-----)逐块解码;没有标记头再按旧语义退回
|
||
// 「任意格式」整串解一次(覆盖只有 base64 正文的锚),最后兜底裸 DER。
|
||
int added = DecodeAllCerts(pem, CRYPT_STRING_BASE64HEADER, store, source, quiet);
|
||
if (added == 0 && pem.find("-----BEGIN") == std::string::npos) {
|
||
std::vector<BYTE> der(pem.size() + 16);
|
||
DWORD cb = (DWORD)der.size();
|
||
if (CryptStringToBinaryA(pem.data(), (DWORD)pem.size(), CRYPT_STRING_ANY,
|
||
der.data(), &cb, NULL, NULL) && AddDerCert(der.data(), cb, store))
|
||
++added;
|
||
// 兜底:正文就是 DER 字节(REG_BINARY / 二进制文件读进来的情况)。
|
||
if (added == 0 && AddDerCert((const BYTE*)pem.data(), (DWORD)pem.size(), store))
|
||
++added;
|
||
}
|
||
if (added == 0) {
|
||
CertCloseStore(store, 0);
|
||
if (!quiet)
|
||
Mprintf("[TLS] failed to decode certificate %s\n", source.c_str());
|
||
return false;
|
||
}
|
||
if (!quiet)
|
||
Mprintf("[TLS] trust anchor %s: %d certificate(s) loaded\n", source.c_str(), added);
|
||
|
||
*outStore = store;
|
||
return true;
|
||
}
|
||
|
||
enum TlsAnchor { TLS_ANCHOR_OK, TLS_ANCHOR_NONE, TLS_ANCHOR_INVALID };
|
||
|
||
// 读取当前信任锚并建好 store + 链引擎(成功时经 outStore/outEngine 交出,调用方负责
|
||
// 释放)。不触碰全局状态。source 描述锚的来源,仅用于日志。
|
||
TlsAnchor BuildTlsAnchor(bool allowEmbedded, bool quiet, HCERTSTORE* outStore,
|
||
HCERTCHAINENGINE* outEngine, std::string& source, std::string& err)
|
||
{
|
||
std::string pem;
|
||
if (!ReadTrustAnchor(pem, source, allowEmbedded, quiet)) {
|
||
err = "no trust anchor configured";
|
||
return TLS_ANCHOR_NONE;
|
||
}
|
||
|
||
HCERTSTORE store = NULL;
|
||
if (!LoadTrustAnchor(pem, source, quiet, &store)) {
|
||
err = "trust anchor (" + source + ") present but failed to load";
|
||
return TLS_ANCHOR_INVALID;
|
||
}
|
||
|
||
// 严格钉扎:链引擎只信任该 store 里的根证书,排除系统根库。否则攻击者拿一张任意
|
||
// 公共 CA 签发的证书就能通过 CertGetCertificateChain(默认引擎信任系统根库)。
|
||
CERT_CHAIN_ENGINE_CONFIG ec = {};
|
||
ec.cbSize = sizeof(ec);
|
||
ec.hExclusiveRoot = store;
|
||
HCERTCHAINENGINE engine = NULL;
|
||
if (!CertCreateCertificateChainEngine(&ec, &engine)) {
|
||
CertCloseStore(store, 0);
|
||
err = "CertCreateCertificateChainEngine failed";
|
||
return TLS_ANCHOR_INVALID;
|
||
}
|
||
|
||
*outStore = store;
|
||
*outEngine = engine;
|
||
return TLS_ANCHOR_OK;
|
||
}
|
||
|
||
void FreeState(TlsState& st)
|
||
{
|
||
if (st.engine) { CertFreeCertificateChainEngine(st.engine); st.engine = NULL; }
|
||
if (st.store) { CertCloseStore(st.store, 0); st.store = NULL; }
|
||
}
|
||
|
||
// 按当前信任锚重建某一套 TLS 状态(调用方持 g_tlsMtx)。idx:1=允许内嵌锚,0=不用。
|
||
// 首次加载失败 → fail-closed(管理员已「颁发」证书,不能静默回退明文);运行期热重载
|
||
// 失败 → 保持现有状态不变,返回 false(一次坏下发不该打死正在工作的客户端;下次启动
|
||
// 仍会 fail-closed)。
|
||
bool ApplyTlsStateLocked(int idx, bool initial, std::string& err, bool quiet)
|
||
{
|
||
HCERTSTORE store = NULL;
|
||
HCERTCHAINENGINE engine = NULL;
|
||
std::string source;
|
||
const TlsAnchor anchor = BuildTlsAnchor(idx == 1, quiet, &store, &engine, source, err);
|
||
TlsState& st = g_state[idx];
|
||
|
||
if (anchor == TLS_ANCHOR_INVALID) {
|
||
if (initial && !st.loaded) {
|
||
FreeState(st);
|
||
st.enabled = st.anchorEmbedded = false;
|
||
st.error = true;
|
||
st.loaded = true;
|
||
st.source = source;
|
||
if (!quiet)
|
||
Mprintf("[TLS] FATAL: %s; refusing connections (fail-closed)\n", err.c_str());
|
||
} else if (!quiet) {
|
||
Mprintf("[TLS] reload failed: %s (keeping current transport)\n", err.c_str());
|
||
}
|
||
return false;
|
||
}
|
||
|
||
// 互换。旧 store/engine 可以直接释放:校验路径持同一把锁,此刻没有线程在用它们。
|
||
FreeState(st);
|
||
st.store = store;
|
||
st.engine = engine;
|
||
st.enabled = (anchor == TLS_ANCHOR_OK);
|
||
st.anchorEmbedded = st.enabled && source == "embedded";
|
||
st.error = false;
|
||
st.loaded = true;
|
||
st.source = source;
|
||
|
||
if (!quiet) {
|
||
if (st.enabled)
|
||
Mprintf("[TLS] enabled: trust anchor loaded (%s), using TLS\n", source.c_str());
|
||
else
|
||
Mprintf("[TLS] disabled: no trust anchor configured, plaintext mode\n");
|
||
}
|
||
return true;
|
||
}
|
||
|
||
// 首次调用时才真正加载;之后一律用缓存的状态(热重载由 TlsReload 负责)。
|
||
//
|
||
// 本连接不走内嵌锚时,两套状态都静默建好,只发一条描述本连接的状态行。不能反过来
|
||
// 先按 idx==1 打了日志再补一句——那两条讲的是本连接不用的那套(实测日志会读成
|
||
// 「skipped → enabled, using TLS → plaintext」,前后自相矛盾)。
|
||
void EnsureStateLocked(int idx)
|
||
{
|
||
if (g_state[idx].loaded)
|
||
return;
|
||
|
||
std::string err;
|
||
if (idx == 1) {
|
||
ApplyTlsStateLocked(1, true, err, false);
|
||
return;
|
||
}
|
||
|
||
ApplyTlsStateLocked(1, true, err, true); // 本连接不用,但其它目标/热重载还要用
|
||
ApplyTlsStateLocked(0, true, err, true);
|
||
const TlsState& st = g_state[0];
|
||
if (st.error)
|
||
Mprintf("[TLS] this connection: fail-closed, trust anchor unusable\n");
|
||
else if (st.enabled)
|
||
Mprintf("[TLS] this connection: TLS with trust anchor (%s)\n", st.source.c_str());
|
||
else
|
||
Mprintf("[TLS] this connection: plaintext mode\n");
|
||
}
|
||
|
||
// 本连接用哪一套状态:目标命中内嵌锚的主控地址就用 [1],否则 [0]。
|
||
// 不持 g_tlsMtx:里面可能解析域名(见 g_matchMtx 的注释),调用方应在取锁**之前**调用。
|
||
int ResolveStateIndex(const std::string& host, const std::string& configured)
|
||
{
|
||
return EmbeddedAnchorAppliesTo(host, configured) ? 1 : 0;
|
||
}
|
||
|
||
} // namespace
|
||
|
||
bool TlsEnabled()
|
||
{
|
||
std::lock_guard<std::mutex> lk(g_tlsMtx);
|
||
EnsureStateLocked(1);
|
||
return g_state[1].enabled;
|
||
}
|
||
|
||
bool TlsLoadError()
|
||
{
|
||
std::lock_guard<std::mutex> lk(g_tlsMtx);
|
||
EnsureStateLocked(1);
|
||
return g_state[1].error;
|
||
}
|
||
|
||
bool TlsEnabledFor(const std::string& host, const std::string& configured)
|
||
{
|
||
const int idx = ResolveStateIndex(host, configured); // DNS 在锁外
|
||
std::lock_guard<std::mutex> lk(g_tlsMtx);
|
||
EnsureStateLocked(idx);
|
||
return g_state[idx].enabled;
|
||
}
|
||
|
||
bool TlsLoadErrorFor(const std::string& host, const std::string& configured)
|
||
{
|
||
const int idx = ResolveStateIndex(host, configured); // DNS 在锁外
|
||
std::lock_guard<std::mutex> lk(g_tlsMtx);
|
||
EnsureStateLocked(idx);
|
||
return g_state[idx].error;
|
||
}
|
||
|
||
bool TlsReload(std::string& err)
|
||
{
|
||
std::lock_guard<std::mutex> lk(g_tlsMtx);
|
||
// 两套一起重建:一套失败按「保持原状」处理(ApplyTlsStateLocked 内部保证),
|
||
// 另一套照常更新。返回 false 表示至少有一套没换成新锚。
|
||
std::string err1, err0;
|
||
const bool ok1 = ApplyTlsStateLocked(1, !g_state[1].loaded, err1, false);
|
||
const bool ok0 = ApplyTlsStateLocked(0, !g_state[0].loaded, err0, true);
|
||
err = ok1 ? err0 : err1;
|
||
return ok1 && ok0;
|
||
}
|
||
|
||
// ---- TlsChannel ----
|
||
|
||
void TlsChannel::CloseHandles()
|
||
{
|
||
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
|
||
if (m_ctxValid) { DeleteSecurityContext(&m_ctx); m_ctx = {}; m_ctxValid = false; }
|
||
if (m_credValid) { FreeCredentialsHandle(&m_cred); m_cred = {}; m_credValid = false; }
|
||
m_ready = false;
|
||
m_raw.clear();
|
||
m_pending.clear();
|
||
}
|
||
|
||
bool TlsChannel::SendAll(SOCKET sock, const void* data, int len)
|
||
{
|
||
const char* p = (const char*)data;
|
||
int sent = 0;
|
||
while (sent < len) {
|
||
int n = ::send(sock, p + sent, len - sent, 0);
|
||
if (n == SOCKET_ERROR || n == 0)
|
||
return false;
|
||
sent += n;
|
||
}
|
||
return true;
|
||
}
|
||
|
||
bool TlsChannel::VerifyServerCert()
|
||
{
|
||
PCCERT_CONTEXT remote = NULL;
|
||
SECURITY_STATUS sc = QueryContextAttributesA(&m_ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, &remote);
|
||
if (sc != SEC_E_OK || !remote)
|
||
return false;
|
||
|
||
// 与 TlsReload 互斥:校验期间持有 g_tlsMtx,重建时释放的旧 store/engine 不会正被使用。
|
||
// 持锁时间很短:建链全是本地操作(DISABLE_AIA 禁联网取中间证书,也不带任何
|
||
// CERT_CHAIN_REVOCATION_CHECK_* 位),不会因为网络等待而卡住 TlsReload。
|
||
std::lock_guard<std::mutex> lk(g_tlsMtx);
|
||
const TlsState& st = g_state[m_stateIdx];
|
||
if (!st.store || !st.engine) {
|
||
CertFreeCertificateContext(remote);
|
||
return false;
|
||
}
|
||
// 本连接实际用的是哪一套信任锚:登录上报 CLIENT_CAP_EMBEDDED_ANCHOR 靠它。
|
||
m_anchorEmbedded = st.anchorEmbedded;
|
||
|
||
CERT_CHAIN_PARA para = {};
|
||
para.cbSize = sizeof(para);
|
||
PCCERT_CHAIN_CONTEXT chain = NULL;
|
||
// st.engine 的 hExclusiveRoot 已把信任锚限制为 st.store;hAdditionalStore 再传一次
|
||
// 该 store 供链引擎查找 CA/中间证书。只接受「无任何错误位」的链(含时间有效性)。
|
||
// 不设置任何 CERT_CHAIN_REVOCATION_CHECK_* 位 = 不做吊销检查(私有 CA 无 CRL/OCSP,
|
||
// 且这些位会触发联网,反而失败);只保留 CERT_CHAIN_DISABLE_AIA 禁止联网取中间证书。
|
||
BOOL ok = CertGetCertificateChain(st.engine, remote, NULL, st.store, ¶,
|
||
CERT_CHAIN_DISABLE_AIA,
|
||
NULL, &chain);
|
||
bool trusted = false;
|
||
if (ok && chain) {
|
||
trusted = (chain->TrustStatus.dwErrorStatus == CERT_TRUST_NO_ERROR);
|
||
}
|
||
if (chain) CertFreeCertificateChain(chain);
|
||
CertFreeCertificateContext(remote);
|
||
return trusted;
|
||
}
|
||
|
||
bool TlsChannel::Handshake(SOCKET sock, const char* sni, const std::string& host,
|
||
const std::string& configured)
|
||
{
|
||
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
|
||
CloseHandles(); // 重连时清理上一次会话(recursive 锁,此处可重入)
|
||
|
||
// 本连接用**哪一套**状态(允许/不允许内嵌锚)在握手开始时定下,之后不再改——地址
|
||
// 匹配只算这一次,而它可能要解析域名,必须在取 g_tlsMtx 之前做完。
|
||
//
|
||
// 注意别把这里读成「锚本身也定死了」:这套状态里的 store/链引擎由 TlsReload 原地
|
||
// 替换,握手末尾的 VerifyServerCert 读的是**此刻**的 g_state[m_stateIdx]。这是有意
|
||
// 为之——服务端刚下发的锚对正在进行的握手也立即生效;两套锚之间不会串,校验只认
|
||
// m_stateIdx 那一套。
|
||
m_anchorEmbedded = false;
|
||
const int idx = ResolveStateIndex(host, configured);
|
||
{
|
||
std::lock_guard<std::mutex> stlk(g_tlsMtx);
|
||
m_stateIdx = idx;
|
||
EnsureStateLocked(idx);
|
||
}
|
||
|
||
SCHANNEL_CRED cred = {};
|
||
cred.dwVersion = SCHANNEL_CRED_VERSION;
|
||
cred.dwFlags = SCH_CRED_MANUAL_CRED_VALIDATION | SCH_CRED_NO_DEFAULT_CREDS;
|
||
cred.grbitEnabledProtocols = SP_PROT_TLS1_2_CLIENT; // TLS 1.2(与 Go 端 MinVersion 对齐)
|
||
|
||
TimeStamp tsExpiry = {};
|
||
SECURITY_STATUS sc = AcquireCredentialsHandleA(
|
||
NULL, (SEC_CHAR*)"Microsoft Unified Security Protocol Provider",
|
||
SECPKG_CRED_OUTBOUND, NULL, &cred, NULL, NULL, &m_cred, &tsExpiry);
|
||
if (sc != SEC_E_OK) {
|
||
Mprintf("[TLS] AcquireCredentialsHandle failed: 0x%08X\n", (unsigned)sc);
|
||
return false;
|
||
}
|
||
m_credValid = true;
|
||
|
||
DWORD flags = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT | ISC_REQ_CONFIDENTIALITY
|
||
| ISC_REQ_ALLOCATE_MEMORY | ISC_REQ_STREAM | ISC_REQ_MANUAL_CRED_VALIDATION;
|
||
|
||
SecBuffer outBuf = { 0, SECBUFFER_TOKEN, NULL };
|
||
SecBufferDesc outDesc = { SECBUFFER_VERSION, 1, &outBuf };
|
||
ULONG attrs = 0;
|
||
|
||
// 首次调用产生 ClientHello。pszTargetName 非空时 Schannel 会把它作为 SNI 发送,
|
||
// 供反代按域名分流;证书校验仍是手动钉信任锚(SCH_CRED_MANUAL_CRED_VALIDATION),
|
||
// 不因传了名字而启用主机名校验。
|
||
sc = InitializeSecurityContextA(&m_cred, NULL, (SEC_CHAR*)sni, flags, 0, SECURITY_NATIVE_DREP,
|
||
NULL, 0, &m_ctx, &outDesc, &attrs, &tsExpiry);
|
||
m_ctxValid = true; // 上下文已分配,之后必须 DeleteSecurityContext
|
||
if (sc != SEC_I_CONTINUE_NEEDED && sc != SEC_E_OK) {
|
||
Mprintf("[TLS] InitializeSecurityContext(initial) failed: 0x%08X\n", (unsigned)sc);
|
||
CloseHandles();
|
||
return false;
|
||
}
|
||
if (outBuf.cbBuffer > 0 && outBuf.pvBuffer) {
|
||
if (!SendAll(sock, outBuf.pvBuffer, (int)outBuf.cbBuffer)) {
|
||
FreeContextBuffer(outBuf.pvBuffer);
|
||
CloseHandles();
|
||
return false;
|
||
}
|
||
FreeContextBuffer(outBuf.pvBuffer);
|
||
}
|
||
|
||
std::vector<BYTE> hs;
|
||
char raw[8192];
|
||
while (sc == SEC_I_CONTINUE_NEEDED || sc == SEC_E_INCOMPLETE_MESSAGE ||
|
||
sc == SEC_I_INCOMPLETE_CREDENTIALS)
|
||
{
|
||
int r = recv(sock, raw, sizeof(raw), 0);
|
||
if (r == SOCKET_ERROR || r == 0) {
|
||
Mprintf("[TLS] handshake recv failed/EOF\n");
|
||
CloseHandles();
|
||
return false;
|
||
}
|
||
hs.insert(hs.end(), (BYTE*)raw, (BYTE*)raw + r);
|
||
|
||
SecBuffer inBufs[2] = {
|
||
{ (ULONG)hs.size(), SECBUFFER_TOKEN, hs.data() },
|
||
{ 0, SECBUFFER_EMPTY, NULL },
|
||
};
|
||
SecBufferDesc inDesc = { SECBUFFER_VERSION, 2, inBufs };
|
||
|
||
outBuf = { 0, SECBUFFER_TOKEN, NULL };
|
||
outDesc = { SECBUFFER_VERSION, 1, &outBuf };
|
||
|
||
sc = InitializeSecurityContextA(&m_cred, &m_ctx, (SEC_CHAR*)sni, flags, 0, SECURITY_NATIVE_DREP,
|
||
&inDesc, 0, NULL, &outDesc, &attrs, &tsExpiry);
|
||
|
||
// 裁剪已消费的输入,仅保留 SECBUFFER_EXTRA 指向的未消费尾部
|
||
if (inBufs[1].BufferType == SECBUFFER_EXTRA) {
|
||
int extra = inBufs[1].cbBuffer;
|
||
int consumed = (int)hs.size() - extra;
|
||
hs.erase(hs.begin(), hs.begin() + consumed);
|
||
} else {
|
||
hs.clear();
|
||
}
|
||
|
||
if (outBuf.cbBuffer > 0 && outBuf.pvBuffer) {
|
||
if (!SendAll(sock, outBuf.pvBuffer, (int)outBuf.cbBuffer)) {
|
||
FreeContextBuffer(outBuf.pvBuffer);
|
||
CloseHandles();
|
||
return false;
|
||
}
|
||
FreeContextBuffer(outBuf.pvBuffer);
|
||
}
|
||
}
|
||
|
||
if (sc != SEC_E_OK) {
|
||
Mprintf("[TLS] handshake failed: 0x%08X\n", (unsigned)sc);
|
||
CloseHandles();
|
||
return false;
|
||
}
|
||
|
||
// 握手成功后 hs 里可能残留「未消费的尾部」= 服务端 Finished 后紧跟的首条应用数据
|
||
// (TLS 记录)。若不下发,首包会被丢弃,导致随机丢包/协议错位。交给 Recv 解。
|
||
if (!hs.empty())
|
||
m_raw.insert(m_raw.end(), hs.begin(), hs.end());
|
||
|
||
if (!VerifyServerCert()) {
|
||
Mprintf("[TLS] server certificate not trusted against yama-ca.pem (fail-closed)\n");
|
||
CloseHandles();
|
||
return false;
|
||
}
|
||
|
||
sc = QueryContextAttributesA(&m_ctx, SECPKG_ATTR_STREAM_SIZES, &m_sizes);
|
||
if (sc != SEC_E_OK) {
|
||
Mprintf("[TLS] QueryContextAttributes(StreamSizes) failed: 0x%08X\n", (unsigned)sc);
|
||
CloseHandles();
|
||
return false;
|
||
}
|
||
|
||
m_ready = true;
|
||
Mprintf("[TLS] handshake OK (TLS 1.2, server cert trusted)\n");
|
||
return true;
|
||
}
|
||
|
||
int TlsChannel::Recv(SOCKET 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;
|
||
}
|
||
|
||
if (!m_pending.empty()) {
|
||
int n = (int)m_pending.size() < outLen ? (int)m_pending.size() : outLen;
|
||
memcpy(out, m_pending.data(), n);
|
||
m_pending.erase(m_pending.begin(), m_pending.begin() + n);
|
||
return n;
|
||
}
|
||
|
||
char raw[16384];
|
||
for (;;) {
|
||
// 优先解密 m_raw 里已缓冲的字节(握手时随 Finished 收下的首条应用数据,或上轮
|
||
// 一次 recv 到多条记录后剩下的记录)。select() 只看底层 socket,看不到这些字节,
|
||
// 若先 recv 就会把它们卡住(随机延迟/死锁/协议错位)。
|
||
while (!m_raw.empty()) {
|
||
SecBuffer bufs[4] = {
|
||
{ (ULONG)m_raw.size(), SECBUFFER_DATA, m_raw.data() },
|
||
{ 0, SECBUFFER_EMPTY, NULL },
|
||
{ 0, SECBUFFER_EMPTY, NULL },
|
||
{ 0, SECBUFFER_EMPTY, NULL },
|
||
};
|
||
SecBufferDesc desc = { SECBUFFER_VERSION, 4, bufs };
|
||
SECURITY_STATUS sc = DecryptMessage(&m_ctx, &desc, 0, NULL);
|
||
|
||
if (sc == SEC_E_INCOMPLETE_MESSAGE)
|
||
break; // 记录不完整,去 recv 补字节
|
||
if (sc == SEC_I_CONTEXT_EXPIRED)
|
||
return 0; // close_notify
|
||
if (sc == SEC_I_RENEGOTIATE || FAILED(sc)) {
|
||
// 客户端解密失败(服务端发来的密文损坏/错位)。这里只返回 SOCKET_ERROR,
|
||
// 而 WSAGetLastError() 会残留上一次 Winsock 调用的旧值(如 6001),
|
||
// 掩盖真实原因,故把真实的 SECURITY_STATUS 记下来。
|
||
Mprintf("[TLS] client DecryptMessage failed 0x%08x (raw=%u pending=%u)\n",
|
||
(unsigned)sc, (unsigned)m_raw.size(), (unsigned)m_pending.size());
|
||
return SOCKET_ERROR;
|
||
}
|
||
|
||
// 流模式 DecryptMessage 会把输入 SECBUFFER_DATA 重组为 4 段:
|
||
// bufs[0]=STREAM_HEADER(记录头+nonce)、bufs[1]=DATA(明文)、
|
||
// bufs[2]=STREAM_TRAILER(标签)、bufs[3]=EXTRA(下一条记录)。
|
||
// 明文在 bufs[1].pvBuffer,不在 m_raw 首字节。
|
||
int decLen = bufs[1].cbBuffer;
|
||
const BYTE* plain = (const BYTE*)bufs[1].pvBuffer;
|
||
int extra = (bufs[3].BufferType == SECBUFFER_EXTRA) ? bufs[3].cbBuffer : 0;
|
||
int consumed = (int)m_raw.size() - extra;
|
||
m_pending.insert(m_pending.end(), plain, plain + decLen);
|
||
m_raw.erase(m_raw.begin(), m_raw.begin() + consumed);
|
||
|
||
if (!m_pending.empty()) {
|
||
int n = (int)m_pending.size() < outLen ? (int)m_pending.size() : outLen;
|
||
memcpy(out, m_pending.data(), n);
|
||
m_pending.erase(m_pending.begin(), m_pending.begin() + n);
|
||
return n;
|
||
}
|
||
// 无明文的记录(如 alert/CCS):继续循环解下一条
|
||
}
|
||
|
||
int r = recv(sock, raw, sizeof(raw), 0);
|
||
if (r == SOCKET_ERROR)
|
||
return SOCKET_ERROR;
|
||
if (r == 0)
|
||
return 0; // 对端关闭(此时无 pending,且 m_raw 已解完/为空)
|
||
m_raw.insert(m_raw.end(), (BYTE*)raw, (BYTE*)raw + r);
|
||
// 循环回顶部,解密刚收到的字节
|
||
}
|
||
}
|
||
|
||
int TlsChannel::Send(SOCKET 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;
|
||
|
||
ULONG maxMsg = m_sizes.cbMaximumMessage > 0 ? m_sizes.cbMaximumMessage : 16384;
|
||
int total = 0;
|
||
while (total < len) {
|
||
int chunk = (len - total > (int)maxMsg) ? (int)maxMsg : (len - total);
|
||
|
||
std::vector<BYTE> rec(m_sizes.cbHeader + chunk + m_sizes.cbTrailer);
|
||
BYTE* hdr = rec.data();
|
||
BYTE* body = hdr + m_sizes.cbHeader;
|
||
BYTE* trailer = body + chunk;
|
||
memcpy(body, data + total, chunk);
|
||
|
||
SecBuffer bufs[4] = {
|
||
{ m_sizes.cbHeader, SECBUFFER_STREAM_HEADER, hdr },
|
||
{ (ULONG)chunk, SECBUFFER_DATA, body },
|
||
{ m_sizes.cbTrailer, SECBUFFER_STREAM_TRAILER, trailer },
|
||
{ 0, SECBUFFER_EMPTY, NULL },
|
||
};
|
||
SecBufferDesc desc = { SECBUFFER_VERSION, 4, bufs };
|
||
SECURITY_STATUS sc = EncryptMessage(&m_ctx, 0, &desc, 0);
|
||
if (FAILED(sc)) {
|
||
return total > 0 ? total : SOCKET_ERROR;
|
||
}
|
||
|
||
int wireLen = bufs[0].cbBuffer + bufs[1].cbBuffer + bufs[2].cbBuffer;
|
||
if (!SendAll(sock, rec.data(), wireLen)) {
|
||
return total > 0 ? total : SOCKET_ERROR;
|
||
}
|
||
total += chunk;
|
||
}
|
||
return total;
|
||
}
|
||
|
||
#endif // _WIN32
|