Files
SimpleRemoter/server/2015Remote/ServerTlsSession.cpp
T
yuanyuanxianganddeepseek-flash c4021e1fc9 Feature: Ship a built-in TLS certificate so encryption works out of the box
A fresh install used to require openssl before the server could speak TLS:
two empty paths in [tls] meant the identity failed to load and every
ClientHello was refused. TLS is now on by default and, when no custom
certificate is configured, the server generates its own self-signed one the
first time it needs it -- RSA-2048, SHA-256, CN=yama-server, CA:TRUE, valid
for ten years from one day before now. Plaintext clients are untouched, since
the device port still splits plaintext from TLS by sniffing the first six
bytes of a connection.

The certificate and its PKCS#8 private key are stored side by side in the
config under [tls] BuiltinCert / BuiltinKey as single-line base64 DER. Single
line, because the server has two config backends -- the registry for Release,
settings.ini for a Debug master -- and only a line without newlines means the
same read/write code serves both. That in turn required fixing the registry
reader: iniFile::GetStr copied into a 512 byte stack buffer, so a 1.5 KB value
came back as a truncated or empty string. The two-phase dynamic read now lives
in common/iniFile.h as ReadRegistryValueSz / ReadRegistrySz, and the copy that
client/TlsChannel.cpp had been carrying for its own trust anchor is gone. This
also makes the built-in certificate self-checking: Ensure() re-reads what it
just wrote and fails loudly if the round trip did not survive.

Import has to go through NCRYPT_PKCS8_PRIVATE_KEY_BLOB, matching the import
path in BuildIdentityFromDer. NCRYPT_PKCS8_PRIV_KEY_INFO_BLOB, which most
samples reach for, is not implemented by the Microsoft Software KSP and
returns NTE_INVALID_PARAMETER; a probe confirmed it, and the export type that
works is the one the importer already expected. Building an identity is now
split into a file front-end (PEM, fullchain, PKCS#1 hints) and a shared DER
core, so the built-in and file paths cannot drift apart.

That key also exposed a second problem worth fixing here. The identity binds
its private key to the certificate by name -- CRYPT_KEY_PROV_INFO with
pwszContainerName -- and Schannel resolves that name on every handshake
through CryptAcquireCertificatePrivateKey. With the fixed name
"YamaServerTlsKey", two server processes under the same Windows user shared
one key slot: whichever loaded last overwrote it, and the other process's next
handshake picked up a private key that does not match its certificate. That is
exactly the debug-plus-release pairing used here, and defaulting to a built-in
certificate is what makes it reachable, since the debug instance no longer
points at the same PEM as the release instance. The name is now the base name
plus the first six bytes of the certificate's SHA-1 thumbprint, e.g.
YamaServerTlsKey-c0d469eae8a4: different certificates get different keys,
instances sharing one certificate still share one key. MCP picks this up too.
The effective name goes to the trace log so a collision is visible without a
debugger. A stale key from an older build may still sit in the key store under
the old name; nothing references it and it is not deleted automatically, since
a running instance of an older build could be using it.

The trust anchor still has to be pushed. The client pins exactly one root
through an exclusive-root chain engine and checks no host name, so a
self-signed CA:TRUE leaf chains cleanly to itself -- but only if the client is
told about it. That is the existing 启用 TLS / 切换到 WSS command, which now
takes the PEM from ServerTlsIdentity::AnchorPem instead of re-reading the
configured cert file, so it reports the same certificate the server actually
serves for both sources. Losing the stored certificate (cleared registry, new
Windows user) regenerates it, and every client must be re-pushed the anchor.

Two places that used to fall back to [tls] CertPath now skip that fallback
while the built-in certificate is active: the MCP HTTPS front end at startup
and the prefill in its settings dialog. A self-signed certificate cannot pass
validation at a public MCP client, and the retained CertPath is only a
leftover from switching back to a custom certificate, so pretending to use it
would fail later with a worse message. MCP HTTPS with empty paths already
fails closed with a log line.

The TLS dialog gains a 内置证书 checkbox, ticked by default and unticked when
certificate paths are present; ticking it greys out the path rows without
clearing them, and shows either "generated on first use" or the expiry date
read back from the stored certificate. Saving writes four keys -- Enabled,
UseBuiltIn, CertPath, KeyPath -- and an explicit UseBuiltIn keeps the paths
from being used as an implicit switch. Every reader of [tls] Enabled now
defaults to 1, so the menu check, the dialog and the loader agree on a fresh
install. The status bar panes on 无 / 有 grew a third state, 内置, and the
pane width is measured across all three.

Translations were added to en_US, zh_TW and de_DE; skipping the German file
would have left the new dialog text in Chinese there, as de_DE is loaded from
disk rather than embedded.

Verified with the debug server against openssl s_client. Both the generated
built-in certificate (CN=yama-server) and an existing custom one
(CN=localhost) complete a TLS 1.2 handshake with the pinned certificate, and
their log lines show distinct key names, c0d469eae8a4 and 272f2adfb19c. An
unmodified client still runs in plaintext without an anchor, an existing custom
certificate deployment behaves exactly as before, and client and server both
build clean at Debug x64.

Co-Authored-By: deepseek-flash
2026-11-01 15:39:54 +01:00

979 lines
38 KiB
C++
Raw Permalink 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.
// ServerTlsSession.cpp — 服务端单向 TLS(Schannel 入站)实现
//
// 与客户端 TlsChannel.cpp 对称,但走 AcceptSecurityContext 入站握手、DecryptMessage/
// EncryptMessage 流式加解密。证书/私钥加载为 PEM + CNG(NCryptImportKey PKCS#8),
// 以便与 Go 服务端(server/go 的 crypto/tls,YAMA_TLS_CERT/KEY)共用同一对密钥。
#include "StdAfx.h"
#include "ServerTlsSession.h"
#include "BuiltinTlsCert.h" // 内置证书(缺省证书来源)
#include "Server.h" // CONTEXT_OBJECT::FreeTls()
#include "common/iniFile.h" // config(GetInt/GetStr)
#include <ncrypt.h>
#include <bcrypt.h>
#include <fstream>
#include <iterator>
#include <sstream>
#pragma comment(lib, "secur32.lib")
#pragma comment(lib, "crypt32.lib")
#pragma comment(lib, "ncrypt.lib")
namespace
{
// 进程级身份(进程启动加载一次;未来 UI/指令热切换时改为引用计数 + 惰性释放)。
std::mutex g_identityMtx;
bool g_enabled = false;
bool g_ready = false;
bool g_loadError = false;
bool g_builtin = false; // 当前身份来自内置证书(状态栏「TLS: 内置」用)
CredHandle g_cred = {};
bool g_credValid = false;
PCCERT_CONTEXT g_cert = NULL; // 与入站凭据同生命周期,FreeIdentity 时释放
NCRYPT_KEY_HANDLE g_persistedKey = 0; // 已持久化到 CNG KSP 的私钥句柄,FreeIdentity 时删除
std::string g_anchorPem; // 当前身份的信任锚 PEM(下发给客户端)
// 持久化私钥在 CNG KSP 中的名字基名。实际键名还会拼上证书指纹(见
// BuildIdentityFromDer),所以换证书不会撞名;同一张证书始终对应同一个键,
// 配合 NCRYPT_OVERWRITE_KEY_FLAG 重启时覆盖旧键,避免残留。
const wchar_t* g_keyName = L"YamaServerTlsKey";
// 一次性读文件为 std::string(二进制安全)。
bool ReadFileText(const std::string& path, std::string& out)
{
std::ifstream f(path, std::ios::binary);
if (!f.is_open())
return false;
std::ostringstream ss;
ss << f.rdbuf();
if (f.bad())
return false;
out = ss.str();
return true;
}
// PEM(-----BEGIN ...----- 包裹的 base64)解码为 DER。失败返回 false。
// CRYPT_STRING_ANY 会自动识别带头的 base64(PEM),对证书与 PKCS#8 私钥均适用。
bool PemToDer(const std::string& pem, std::vector<BYTE>& der)
{
if (pem.empty())
return false;
DWORD need = 0;
if (!CryptStringToBinaryA(pem.data(), (DWORD)pem.size(), CRYPT_STRING_ANY,
NULL, &need, NULL, NULL))
return false;
der.resize(need);
return CryptStringToBinaryA(pem.data(), (DWORD)pem.size(), CRYPT_STRING_ANY,
der.data(), &need, NULL, NULL) == TRUE;
}
// 从 PEM 文本里定位私钥块的类型,用于给出可操作的错误提示。
enum KeyFmt { KF_PKCS8, KF_PKCS1, KF_UNKNOWN };
KeyFmt DetectKeyFormat(const std::string& keyPem)
{
if (keyPem.find("-----BEGIN PRIVATE KEY-----") != std::string::npos)
return KF_PKCS8;
if (keyPem.find("-----BEGIN RSA PRIVATE KEY-----") != std::string::npos ||
keyPem.find("-----BEGIN EC PRIVATE KEY-----") != std::string::npos)
return KF_PKCS1;
return KF_UNKNOWN;
}
// 证书文件里可能有多个 PEM 块(fullchain:叶证书 + 中间证书)。逐块切出来解码,
// 顺序即文件顺序。单证书文件也走这里(返回 1 块)。
std::vector<std::vector<BYTE>> PemToDerList(const std::string& pem)
{
static const std::string kBegin = "-----BEGIN CERTIFICATE-----";
static const std::string kEnd = "-----END CERTIFICATE-----";
std::vector<std::vector<BYTE>> out;
size_t pos = 0;
while (true)
{
size_t b = pem.find(kBegin, pos);
if (b == std::string::npos)
break;
size_t e = pem.find(kEnd, b);
if (e == std::string::npos)
break;
e += kEnd.size();
std::vector<BYTE> der;
if (PemToDer(pem.substr(b, e - b), der) && !der.empty())
out.push_back(std::move(der));
pos = e;
}
return out;
}
}
// =====================================================================================
// ServerTlsIdentity —— 进程级服务端身份(可重入加载,禁止 call_once,供未来热切换)
// =====================================================================================
void ServerTlsIdentity::FreeIdentity()
{
// 先释放凭据,再释放证书上下文,最后删除持久化私钥(凭据/证书可能仍按名引用该键)。
if (g_credValid)
{
FreeCredentialsHandle(&g_cred);
g_credValid = false;
}
g_cred = {};
if (g_cert)
{
CertFreeCertificateContext(g_cert);
g_cert = NULL;
}
if (g_persistedKey)
{
NCryptDeleteKey(g_persistedKey, 0); // 删除并释放句柄
g_persistedKey = 0;
}
}
bool ServerTlsIdentity::Load(config& cfg)
{
std::lock_guard<std::mutex> lk(g_identityMtx);
// 缺省启用:全新部署没有 [tls] Enabled 键时按启用处理,此时证书来源默认是内置证书
// (首次启用时自动生成)。明文客户端不受影响——设备端口按 ClientHello 嗅探分流。
bool enabled = cfg.GetInt("tls", "Enabled", 1) != 0;
const bool builtin = BuiltinTlsCert::UseBuiltin(cfg);
std::string certPath = cfg.GetStr("tls", "CertPath", "");
std::string keyPath = cfg.GetStr("tls", "KeyPath", "");
g_enabled = enabled;
// 先释放旧身份(本轮只在启动时调用一次,不存在「旧身份仍被并发握手使用」的问题;
// 未来热切换需先引用计数、再惰性释放旧凭据)。
FreeIdentity();
g_ready = false;
g_loadError = false;
g_builtin = false;
g_anchorPem.clear();
if (!enabled)
{
Mprintf("[TLS] server TLS disabled ([tls] Enabled=0) — plaintext only\n");
return true;
}
if (builtin)
{
std::vector<BYTE> certDer, keyDer;
if (!BuiltinTlsCert::Ensure(cfg) || !BuiltinTlsCert::ReadDer(cfg, certDer, keyDer))
{
g_loadError = true;
Mprintf("[TLS] FATAL: [tls] builtin certificate unavailable; "
"refusing TLS ClientHello (fail-closed)\n");
return false;
}
if (!LoadIdentityFromDer(certDer, keyDer))
{
g_loadError = true;
return false;
}
// 下发给客户端的信任锚 = 内置自签证书本身(客户端严格 pin 这一张)。
g_anchorPem = BuiltinTlsCert::CertPem(cfg);
g_builtin = true;
g_ready = true;
Mprintf("[TLS] server TLS enabled: builtin certificate\n");
return true;
}
if (certPath.empty() || keyPath.empty())
{
g_loadError = true;
Mprintf("[TLS] FATAL: [tls] Enabled=1 but CertPath/KeyPath empty; "
"refusing TLS ClientHello (fail-closed)\n");
return false;
}
if (!LoadIdentity(certPath, keyPath))
{
g_loadError = true;
return false;
}
// 信任锚 = 证书文件全文:fullchain 场景下中间证书也要一并下发,客户端才能建链。
if (!ReadFileText(certPath, g_anchorPem))
g_anchorPem.clear();
g_ready = true;
Mprintf("[TLS] server TLS enabled: cert=%s key=%s\n", certPath.c_str(), keyPath.c_str());
return true;
}
namespace
{
// 用证书上下文换入站凭据:显式指定服务端证书,不请求客户端证书(单向 TLS)。
// 单独成函数,因为 EC 键的几种绑定方式都要靠「凭据能否建立」来验证。
SECURITY_STATUS AcquireInboundCredFor(PCCERT_CONTEXT cert, CredHandle& cred)
{
SCHANNEL_CRED sc = {};
sc.dwVersion = SCHANNEL_CRED_VERSION;
sc.cCreds = 1;
sc.paCred = &cert;
sc.grbitEnabledProtocols = SP_PROT_TLS1_2_SERVER;
// NO_DEFAULT_CREDS 避免回退到系统默认凭据,确保只用我们提供的证书/私钥。
//(单向 TLS 不请求客户端证书,故无需 SCH_CRED_MANUAL_CRED_VALIDATION。)
sc.dwFlags = SCH_CRED_NO_DEFAULT_CREDS;
cred = {};
TimeStamp tsExpiry = {};
return AcquireCredentialsHandleA(
NULL, (SEC_CHAR*)"Microsoft Unified Security Protocol Provider", SECPKG_CRED_INBOUND,
NULL, &sc, NULL, NULL, &cred, &tsExpiry);
}
// 按「DER 证书链 + PKCS#8 私钥 DER」与 CNG 持久化键名构造一份入站身份。
// 文件证书(BuildIdentity)、内置证书(BuiltinTlsCert)与 MCP 前端(独立键名)共用这段
// 逻辑;键名不同则多份身份可并存,互不覆盖。source 仅用于日志定位。
// 成功时 outCred / outCert / outKey 均有效,生命周期由调用方释放。
bool BuildIdentityFromDer(const std::vector<std::vector<BYTE>>& certDers,
const std::vector<BYTE>& keyDer,
const char* source,
const wchar_t* keyName,
CredHandle& outCred, PCCERT_CONTEXT& outCert, NCRYPT_KEY_HANDLE& outKey)
{
if (certDers.empty())
{
Mprintf("[TLS] FATAL: empty certificate for %s\n", source ? source : "?");
return false;
}
// 1) 证书:DER → PCCERT_CONTEXT(第一块为叶证书)。
PCCERT_CONTEXT cert = CertCreateCertificateContext(X509_ASN_ENCODING,
certDers[0].data(), (DWORD)certDers[0].size());
if (cert == NULL)
{
Mprintf("[TLS] FATAL: CertCreateCertificateContext failed (%u)\n", GetLastError());
return false;
}
// fullchain 里剩下的中间证书要补进「当前用户\中间证书颁发机构」库里:Schannel 的
// 握手在进程外完成,建链时只查系统证书库——塞进叶证书自带的内存库或 paCred 数组都
// 不会被下发(实测只发叶证书,缺中间证书的客户端建链失败)。补进库里之后 Schannel
// 会随握手把整条链下发,这与 .NET SslStreamCertificateContext 的做法一致。
// 已经是公开信息,留在库里无害;已在库中则跳过。
for (size_t i = 1; i < certDers.size(); ++i)
{
PCCERT_CONTEXT chainCert = CertCreateCertificateContext(
X509_ASN_ENCODING, certDers[i].data(), (DWORD)certDers[i].size());
if (chainCert == NULL)
{
Mprintf("[TLS] WARN: chain cert #%u in %s is unreadable (%u); "
"handshake will only send the certificates already in the store\n",
(unsigned)i, source ? source : "?", GetLastError());
continue;
}
static HCERTSTORE s_caStore = NULL; // 进程级;关掉反而让 Schannel 后续取不到
if (s_caStore == NULL)
s_caStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, 0,
CERT_SYSTEM_STORE_CURRENT_USER, L"CA");
bool inStore = s_caStore != NULL &&
CertFindCertificateInStore(s_caStore, X509_ASN_ENCODING, 0,
CERT_FIND_EXISTING, chainCert, NULL) != NULL;
if (!inStore &&
(s_caStore == NULL ||
!CertAddEncodedCertificateToStore(s_caStore, X509_ASN_ENCODING,
certDers[i].data(), (DWORD)certDers[i].size(),
CERT_STORE_ADD_USE_EXISTING, NULL)))
{
Mprintf("[TLS] WARN: cannot add chain cert #%u from %s to the user CA store (%u); "
"handshake may not send the full chain\n",
(unsigned)i, source ? source : "?", GetLastError());
}
CertFreeCertificateContext(chainCert);
}
// 持久化键名 = 调用方给的基名 + 证书指纹前缀。
//
// 为什么不能只用固定键名:私钥是按名绑到证书上的(下面的 CERT_KEY_PROV_INFO),
// Schannel 每次握手都经 CryptAcquireCertificatePrivateKey 用这个名去 KSP 重开私钥。
// 同一个 Windows 用户下同时跑 Debug 与 Release 两个服务端实例(证书各不相同)时,
// 后加载的实例会把同名键覆盖掉,先加载的实例下一次握手就拿到一把与证书不匹配的私钥,
// 握手直接失败。键名带上证书指纹后,不同证书各占一个键;同一张证书(多实例共用一份
// PEM,例如内置证书与自定义证书指向同一对文件)仍然共用同一个键,与既有部署一致。
std::wstring effectiveKeyName(keyName);
{
BYTE hash[20] = {};
DWORD cbHash = sizeof(hash);
if (CertGetCertificateContextProperty(cert, CERT_SHA1_HASH_PROP_ID, hash, &cbHash) &&
cbHash >= 6)
{
static const WCHAR kHex[] = L"0123456789abcdef";
effectiveKeyName += L'-';
for (int i = 0; i < 6; ++i)
{
effectiveKeyName += kHex[hash[i] >> 4];
effectiveKeyName += kHex[hash[i] & 0x0F];
}
}
else
{
// 拿不到指纹就退回固定键名:只是失去多实例隔离,不影响单实例工作。
Mprintf("[TLS] WARN: cannot read cert thumbprint for %s (%u); "
"using fixed key name %ls\n",
source ? source : "?", GetLastError(), keyName);
}
}
// 2) 私钥:PKCS#8 DER → 持久化到 CNG KSP(文件版的 PEM→DER 与 PKCS#1 提示在
// BuildIdentity 里做,内置证书本来就是 PKCS#8 DER)。
//
// 关键:Schannel 入站凭据(AcquireCredentialsHandle)需要「能按名重开」的持久化私钥。
// 匿名临时键不行:绑定 CERT_NCRYPT_KEY_HANDLE_PROP_ID 或 CERT_KEY_CONTEXT_PROP_ID
// 后 Schannel 仍拿不到(AcquireCredentialsHandle 返回 SEC_E_NO_CREDENTIALS 0x8009030e)。
// 最后由 CERT_KEY_PROV_INFO_PROP_ID 按名引用持久化键。
//
// 私钥类型沿用证书公钥类型(早期版本写死 RSA,对 Let's Encrypt 现默认的 ECDSA 证书
// 导裸 BLOB 会拿 NTE_BAD_TYPE 0x8009000a,必须按 EC BLOB 导出)。判断用证书而不是
// NCryptGetProperty(BCRYPT_ALGORITHM_NAME):导入的临时键不支持该属性(实测
// NTE_NOT_SUPPORTED 0x80090029);且私钥本就该与证书匹配。
const char* certKeyOid = cert->pCertInfo->SubjectPublicKeyInfo.Algorithm.pszObjId;
const bool certKeyIsRsa = certKeyOid && strcmp(certKeyOid, szOID_RSA_RSA) == 0;
const bool certKeyIsEc = certKeyOid && strcmp(certKeyOid, szOID_ECC_PUBLIC_KEY) == 0;
if (!certKeyIsRsa && !certKeyIsEc)
{
Mprintf("[TLS] FATAL: cert %s uses unsupported public key type (%s); "
"RSA and ECDSA (P-256/P-384/P-521) are supported\n",
source ? source : "?", certKeyOid ? certKeyOid : "unknown");
CertFreeCertificateContext(cert);
return false;
}
// ECDSA 只支持具名曲线:曲线在证书公钥参数里是 DER 编码的曲线 OID,先核对一遍,
// 好给出比 KSP 报错更清楚的提示(显式参数形式的曲线 KSP 也不吃)。
if (certKeyIsEc)
{
static const BYTE kP256[] = { 0x06,0x08,0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x07 };
static const BYTE kP384[] = { 0x06,0x05,0x2B,0x81,0x04,0x00,0x22 };
static const BYTE kP521[] = { 0x06,0x05,0x2B,0x81,0x04,0x00,0x23 };
const CRYPT_OBJID_BLOB& parm = cert->pCertInfo->SubjectPublicKeyInfo.Algorithm.Parameters;
auto isCurve = [&](const BYTE* der, DWORD len) {
return parm.cbData == len && parm.pbData && memcmp(parm.pbData, der, len) == 0;
};
if (!isCurve(kP256, sizeof(kP256)) && !isCurve(kP384, sizeof(kP384)) &&
!isCurve(kP521, sizeof(kP521)))
{
Mprintf("[TLS] FATAL: cert %s uses an ECDSA curve other than P-256/P-384/P-521 "
"(or explicit curve parameters); convert it to an RSA or named-curve key\n",
source ? source : "?");
CertFreeCertificateContext(cert);
return false;
}
}
NCRYPT_KEY_HANDLE persistedKey = 0;
if (!keyDer.empty())
{
// 显式打开 Microsoft Software Key Storage Provider。hProvider 传 NULL 会让
// NCryptImportKey 走「默认提供者」解析,实测返回 NTE_INVALID_HANDLE(0x80090026),
// 故必须显式取得 KSP 句柄(临时键独立于 hProv,导入后即可释放)。
NCRYPT_PROV_HANDLE hProv = 0;
SECURITY_STATUS st = NCryptOpenStorageProvider(&hProv, MS_KEY_STORAGE_PROVIDER, 0);
if (st != ERROR_SUCCESS)
{
Mprintf("[TLS] FATAL: NCryptOpenStorageProvider failed 0x%08x\n", (unsigned)st);
CertFreeCertificateContext(cert);
return false;
}
// EC 与 RSA 的落盘路径不同:
// - EC:MS Software KSP 唯一支持的「导入私钥并落盘」方式,是在导入参数表里给出
// 键名(NCRYPTBUFFER_PKCS_KEY_NAME)——不带键名一律按匿名临时键处理。同为导入
// 后的持久化,CreatePersistedKey 后写私钥 BLOB 虽然 SetProperty 返回 0,Finalize
// 却给 NTE_INVALID_PARAMETER(0x80090027);导入后再
// NCryptSetProperty(NCRYPT_NAME_PROPERTY) 给 NTE_NOT_SUPPORTED(0x80090029)。
// - RSA:导入为临时键 → 导出裸私钥 BLOB(NCryptSetProperty 只认裸 BLOB,不认
// PKCS#8)→ 写入持久化键 → finalize。
if (certKeyIsEc)
{
std::wstring nameW(effectiveKeyName);
NCryptBuffer nameBuf = {};
nameBuf.cbBuffer = (ULONG)((nameW.size() + 1) * sizeof(WCHAR));
nameBuf.BufferType = NCRYPTBUFFER_PKCS_KEY_NAME;
nameBuf.pvBuffer = (PVOID)nameW.c_str();
NCryptBufferDesc desc = {};
desc.ulVersion = NCRYPTBUFFER_VERSION;
desc.cBuffers = 1;
desc.pBuffers = &nameBuf;
st = NCryptImportKey(hProv, NULL, NCRYPT_PKCS8_PRIVATE_KEY_BLOB, &desc,
&persistedKey, const_cast<PBYTE>(keyDer.data()), (DWORD)keyDer.size(),
NCRYPT_OVERWRITE_KEY_FLAG);
}
else
{
NCRYPT_KEY_HANDLE tmp = 0;
st = NCryptImportKey(hProv, NULL, NCRYPT_PKCS8_PRIVATE_KEY_BLOB, NULL,
&tmp, const_cast<PBYTE>(keyDer.data()), (DWORD)keyDer.size(), 0);
if (st == ERROR_SUCCESS)
{
DWORD policy = NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG | NCRYPT_ALLOW_EXPORT_FLAG;
NCryptSetProperty(tmp, NCRYPT_EXPORT_POLICY_PROPERTY,
(PBYTE)&policy, sizeof(policy), 0);
std::vector<BYTE> raw;
DWORD rawLen = 0;
st = NCryptExportKey(tmp, NULL, BCRYPT_RSAFULLPRIVATE_BLOB, NULL,
NULL, 0, &rawLen, 0);
if (st == ERROR_SUCCESS)
{
raw.resize(rawLen);
st = NCryptExportKey(tmp, NULL, BCRYPT_RSAFULLPRIVATE_BLOB, NULL,
raw.data(), rawLen, &rawLen, 0);
}
if (st == ERROR_SUCCESS)
{
st = NCryptCreatePersistedKey(hProv, &persistedKey, BCRYPT_RSA_ALGORITHM,
effectiveKeyName.c_str(), AT_KEYEXCHANGE,
NCRYPT_OVERWRITE_KEY_FLAG);
}
if (st == ERROR_SUCCESS)
{
st = NCryptSetProperty(persistedKey, BCRYPT_RSAFULLPRIVATE_BLOB,
raw.data(), (DWORD)raw.size(), 0);
}
if (st == ERROR_SUCCESS)
st = NCryptFinalizeKey(persistedKey, 0);
NCryptFreeObject(tmp);
}
}
NCryptFreeObject(hProv);
if (st != ERROR_SUCCESS)
{
Mprintf("[TLS] FATAL: failed to persist PKCS#8 key for %s (0x%08x)\n",
source ? source : "?", (unsigned)st);
if (persistedKey)
NCryptFreeObject(persistedKey);
CertFreeCertificateContext(cert);
return false;
}
}
else
{
Mprintf("[TLS] FATAL: empty private key for %s\n", source ? source : "?");
CertFreeCertificateContext(cert);
return false;
}
// 3) 绑定私钥到证书上下文:按名引用持久化键。Schannel 经 CryptAcquireCertificatePrivateKey
// 在 MS_KEY_STORAGE_PROVIDER 里用 pwszContainerName 重开该键。
// 4) 换入站凭据(单向 TLS,不请求客户端证书)。
CRYPT_KEY_PROV_INFO provInfo = {};
provInfo.pwszContainerName = const_cast<LPWSTR>(effectiveKeyName.c_str());
provInfo.pwszProvName = (LPWSTR)MS_KEY_STORAGE_PROVIDER;
provInfo.dwProvType = 0; // 0 = CNG(无 CAPI provider type)
provInfo.dwKeySpec = certKeyIsEc ? 0 : AT_KEYEXCHANGE; // ECDSA 键无 legacy key spec
CredHandle cred = {};
SECURITY_STATUS st = SEC_E_NO_CREDENTIALS;
if (!CertSetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID, 0, &provInfo))
{
st = (SECURITY_STATUS)HRESULT_FROM_WIN32(GetLastError());
Mprintf("[TLS] FATAL: CertSetCertificateContextProperty(CERT_KEY_PROV_INFO_PROP_ID) "
"failed 0x%08x\n", (unsigned)st);
}
else
{
st = AcquireInboundCredFor(cert, cred);
}
if (st != SEC_E_OK)
{
Mprintf("[TLS] FATAL: AcquireCredentialsHandle(SECPKG_CRED_INBOUND) failed 0x%08x\n",
(unsigned)st);
CertFreeCertificateContext(cert); // 无凭据引用,安全释放
NCryptDeleteKey(persistedKey, 0); // 回滚:删除已持久化的私钥,避免残留
return false;
}
// 键名进日志:排查「两个实例抢同一个持久化键」时,一眼能看出各自用的是哪个键。
Mprintf("[TLS] identity ready: %s (CNG key %ls)\n",
source ? source : "?", effectiveKeyName.c_str());
outCert = cert;
outKey = persistedKey;
outCred = cred;
return true;
}
// 文件版:读证书/私钥 PEM(证书可以是 fullchain),转 DER 后走上面的共用构造逻辑。
bool BuildIdentity(const std::string& certPath, const std::string& keyPath,
const wchar_t* keyName,
CredHandle& outCred, PCCERT_CONTEXT& outCert, NCRYPT_KEY_HANDLE& outKey)
{
std::string certPem, keyPem;
if (!ReadFileText(certPath, certPem))
{
Mprintf("[TLS] FATAL: cannot read cert file %s\n", certPath.c_str());
return false;
}
if (!ReadFileText(keyPath, keyPem))
{
Mprintf("[TLS] FATAL: cannot read key file %s\n", keyPath.c_str());
return false;
}
std::vector<std::vector<BYTE>> certDers = PemToDerList(certPem);
if (certDers.empty())
{
Mprintf("[TLS] FATAL: cert file %s is not a valid PEM\n", certPath.c_str());
return false;
}
// 仅支持 PKCS#8;PKCS#1 给出可操作的转换提示。
if (DetectKeyFormat(keyPem) != KF_PKCS8)
{
Mprintf("[TLS] FATAL: key file %s must be PKCS#8 (-----BEGIN PRIVATE KEY-----). "
"Convert with: openssl pkcs8 -topk8 -nocrypt -in %s -out %s\n",
keyPath.c_str(), keyPath.c_str(), keyPath.c_str());
return false;
}
std::vector<BYTE> keyDer;
if (!PemToDer(keyPem, keyDer))
{
Mprintf("[TLS] FATAL: key file %s is not a valid PEM\n", keyPath.c_str());
return false;
}
return BuildIdentityFromDer(certDers, keyDer, certPath.c_str(), keyName, outCred, outCert, outKey);
}
// 把构造好的身份交给进程级生命周期(FreeIdentity 按序释放)。
void AdoptIdentity(CredHandle cred, PCCERT_CONTEXT cert, NCRYPT_KEY_HANDLE key)
{
// 证书上下文的生命周期交给 g_cert,随 FreeIdentity 释放,
// 保证在 FreeCredentialsHandle 之前私钥一直可用。
g_cred = cred;
g_cert = cert;
g_persistedKey = key;
g_credValid = true;
}
} // namespace
bool ServerTlsIdentity::LoadIdentity(const std::string& certPath, const std::string& keyPath)
{
CredHandle cred = {};
PCCERT_CONTEXT cert = NULL;
NCRYPT_KEY_HANDLE key = 0;
if (!BuildIdentity(certPath, keyPath, g_keyName, cred, cert, key))
return false;
AdoptIdentity(cred, cert, key);
return true;
}
bool ServerTlsIdentity::LoadIdentityFromDer(const std::vector<BYTE>& certDer,
const std::vector<BYTE>& keyDer)
{
CredHandle cred = {};
PCCERT_CONTEXT cert = NULL;
NCRYPT_KEY_HANDLE key = 0;
std::vector<std::vector<BYTE>> certDers(1, certDer);
if (!BuildIdentityFromDer(certDers, keyDer, "builtin", g_keyName, cred, cert, key))
return false;
AdoptIdentity(cred, cert, key);
return true;
}
bool ServerTlsIdentity::IsEnabled()
{
std::lock_guard<std::mutex> lk(g_identityMtx);
return g_enabled;
}
bool ServerTlsIdentity::IsReady()
{
std::lock_guard<std::mutex> lk(g_identityMtx);
return g_ready && g_credValid;
}
bool ServerTlsIdentity::IsLoadError()
{
std::lock_guard<std::mutex> lk(g_identityMtx);
return g_loadError;
}
bool ServerTlsIdentity::IsBuiltin()
{
std::lock_guard<std::mutex> lk(g_identityMtx);
return g_ready && g_credValid && g_builtin;
}
CredHandle ServerTlsIdentity::Cred()
{
std::lock_guard<std::mutex> lk(g_identityMtx);
return g_cred;
}
bool ServerTlsIdentity::AnchorPem(std::string& out)
{
std::lock_guard<std::mutex> lk(g_identityMtx);
if (!g_ready || g_anchorPem.empty())
return false;
out = g_anchorPem;
return true;
}
// =====================================================================================
// ServerTlsSession —— 单连接会话(握手 + 加解密)
// =====================================================================================
void ServerTlsSession::CloseHandles()
{
if (m_ctxValid)
{
DeleteSecurityContext(&m_ctx);
m_ctxValid = false;
}
m_ctx = {};
m_ready = false;
m_raw.clear();
}
// 握手线程在 IOCP 的子套接字上做同步 I/O。该套接字可能是非阻塞的(监听套接字经
// WSAEventSelect 置为非阻塞后,accept 出的子套接字继承非阻塞态;线程里 FIONBIO=0 也
// 不一定即时生效)。故 recv/send 遇 WSAEWOULDBLOCK 时用 select 等可读/可写再重试,
// 而非当致命错误,避免「客户端回包还没到就误判握手失败」。
static bool WaitSocketReady(SOCKET sock, bool forRead, int timeoutMs)
{
fd_set fds;
FD_ZERO(&fds);
FD_SET(sock, &fds);
timeval tv;
tv.tv_sec = timeoutMs / 1000;
tv.tv_usec = (timeoutMs % 1000) * 1000;
return select(0, forRead ? &fds : NULL, forRead ? NULL : &fds, NULL, &tv) > 0;
}
bool ServerTlsSession::SendAll(SOCKET sock, const void* data, int len)
{
const BYTE* p = (const BYTE*)data;
int sent = 0;
while (sent < len)
{
int n = send(sock, (const char*)p + sent, len - sent, 0);
if (n == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
{
if (!WaitSocketReady(sock, false, 15000))
return false;
continue; // 非阻塞套接字发送缓冲满:等可写后重试
}
if (n <= 0)
return false;
sent += n;
}
return true;
}
bool ServerTlsSession::Handshake(SOCKET sock, const BYTE* initial, int initialLen)
{
return HandshakeWithCred(sock, initial, initialLen, ServerTlsIdentity::Cred());
}
bool ServerTlsSession::HandshakeWithCred(SOCKET sock, const BYTE* initial, int initialLen,
CredHandle cred)
{
std::lock_guard<std::mutex> lk(m_mtx);
if (m_ctxValid)
CloseHandles(); // 防御:会话应只握手一次
// 单向 TLS:服务端不请求客户端证书,故无需 ASC_REQ_MANUAL_CRED_VALIDATION
//(该标志只在 mTLS 校验客户端证书时有意义;SDK 的 ASC 命名空间里亦无此常量)。
DWORD req = ASC_REQ_SEQUENCE_DETECT | ASC_REQ_REPLAY_DETECT | ASC_REQ_CONFIDENTIALITY |
ASC_REQ_ALLOCATE_MEMORY | ASC_REQ_STREAM;
std::vector<BYTE> hs;
if (initial != NULL && initialLen > 0)
hs.assign(initial, initial + initialLen);
CtxtHandle ctx = {};
bool ctxValid = false;
TimeStamp tsExpiry = {};
ULONG attrs = 0;
SECURITY_STATUS sc = SEC_I_CONTINUE_NEEDED;
// 握手期间同步收字节:非阻塞套接字上等可读再收,避免误判为致命错误。
auto RecvMore = [&](std::vector<BYTE>& buf) -> bool
{
char raw[8192];
int r;
for (;;)
{
r = recv(sock, raw, sizeof(raw), 0);
if (r == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
{
if (!WaitSocketReady(sock, true, 15000))
{
r = SOCKET_ERROR;
break; // 等可读超时
}
continue;
}
break;
}
if (r <= 0)
{
Mprintf("[TLS] handshake recv failed/EOF (r=%d err=%d)\n", r, WSAGetLastError());
return false;
}
buf.insert(buf.end(), (BYTE*)raw, (BYTE*)raw + r);
return true;
};
// 首次 AcceptSecurityContext 之前必须凑齐一整条 TLS 记录(5 字节头 + 负载)。
// 实测(2026-10-26):用「半条 ClientHello」做首次调用,Schannel 会建出一个坏上下文,
// 之后补齐数据再送返回 SEC_E_UNKNOWN_CREDENTIALS(0x80090301),握手必失败。设备端口
// 一直整包到达所以没暴露;MCP TLS 前端按 8 字节嗅探后接手,稳定触发。故在此统一兜底:
// 调用方给多少都行,缺的字节由本函数从 socket 补齐。
for (;;)
{
if (hs.size() < 5)
{
if (!RecvMore(hs))
return false;
continue;
}
if (hs[0] != 0x16)
{
Mprintf("[TLS] handshake: first byte 0x%02x is not a handshake record; fail-closed\n", hs[0]);
return false;
}
const size_t recLen = 5 + (((size_t)hs[3] << 8) | (size_t)hs[4]);
if (recLen > 18432) // TLS 记录上限 16384 + 允许的额外开销
{
Mprintf("[TLS] handshake: absurd record length %u; fail-closed\n", (unsigned)recLen);
return false;
}
if (hs.size() >= recLen)
break;
if (!RecvMore(hs))
return false;
}
for (;;)
{
SecBuffer inBufs[2] = {
{ (ULONG)hs.size(), SECBUFFER_TOKEN, hs.empty() ? NULL : hs.data() },
{ 0, SECBUFFER_EMPTY, NULL },
};
SecBufferDesc inDesc = { SECBUFFER_VERSION, 2, inBufs };
SecBuffer outBuf = { 0, SECBUFFER_TOKEN, NULL };
SecBufferDesc outDesc = { SECBUFFER_VERSION, 1, &outBuf };
sc = AcceptSecurityContext(&cred, ctxValid ? &ctx : NULL, &inDesc, req,
SECURITY_NATIVE_DREP, ctxValid ? NULL : &ctx,
&outDesc, &attrs, &tsExpiry);
ctxValid = true;
// 发出服务端握手记录(ServerHello/Certificate/... 或 Finished)。
if (outBuf.cbBuffer > 0 && outBuf.pvBuffer)
{
bool ok = SendAll(sock, outBuf.pvBuffer, (int)outBuf.cbBuffer);
FreeContextBuffer(outBuf.pvBuffer);
if (!ok)
{
sc = SEC_E_INTERNAL_ERROR;
break;
}
}
// 计算已消费字节:SECBUFFER_EXTRA 里是「未消费的尾部」(下一条握手消息 / 首条应用数据)。
// 必须在 SEC_E_OK / 失败判定之前处理:否则握手完成时 hs 里仍混着已消费的握手记录,
// 紧跟 Finished 的首条应用数据(客户端登录包)会随 hs 一起被丢弃,导致随机丢包。
if (inBufs[1].BufferType == SECBUFFER_EXTRA)
{
int extra = (int)inBufs[1].cbBuffer;
hs.erase(hs.begin(), hs.begin() + (hs.size() - extra));
}
else if (sc != SEC_E_INCOMPLETE_MESSAGE && sc != SEC_I_INCOMPLETE_CREDENTIALS)
{
hs.clear(); // 已全部消费,继续等下一轮握手消息
}
// 否则:SEC_E_INCOMPLETE_MESSAGE —— 保留 hs(不完整消息),续收补齐。
if (sc == SEC_E_OK)
break;
if (FAILED(sc) && sc != SEC_E_INCOMPLETE_MESSAGE && sc != SEC_I_INCOMPLETE_CREDENTIALS)
{
Mprintf("[TLS] AcceptSecurityContext failed 0x%08x (in=%u consumed? extra=%u)\n",
(unsigned)sc, inBufs[0].cbBuffer, inBufs[1].BufferType == SECBUFFER_EXTRA ? inBufs[1].cbBuffer : 0);
break; // 真正的失败
}
if (!RecvMore(hs))
{
sc = SEC_E_INTERNAL_ERROR;
break;
}
}
if (sc != SEC_E_OK)
{
Mprintf("[TLS] handshake failed: final status 0x%08x (fail-closed)\n", (unsigned)sc);
if (ctxValid)
DeleteSecurityContext(&ctx);
return false;
}
// 握手成功后 hs 里残留的「未消费尾部」是紧跟 Finished 的首条应用数据(TLS 记录)。
// 交给 Decrypt 处理,否则首包会丢(表现为随机登录超时/重连/协议错位)。
if (!hs.empty())
m_raw.insert(m_raw.end(), hs.begin(), hs.end());
// 查询流式记录尺寸(加密封装用)。
SecPkgContext_StreamSizes sizes = {};
if (QueryContextAttributes(&ctx, SECPKG_ATTR_STREAM_SIZES, &sizes) != SEC_E_OK)
{
DeleteSecurityContext(&ctx);
return false;
}
m_ctx = ctx;
m_ctxValid = true;
m_sizes = sizes;
m_ready = true;
return true;
}
int ServerTlsSession::Decrypt(const BYTE* cipher, int len, std::vector<BYTE>& plain)
{
std::lock_guard<std::mutex> lk(m_mtx);
if (!m_ready)
return -1;
// len == 0 表示「只取残留」:握手结束时会话里可能已经躺着紧随 Finished 的首条
// 应用数据(见 HandshakeWithCred 末尾),调用方必须在进入收发循环前取一次,
// 否则这份数据要等下一条密文到达才会被解出来。
if (len > 0)
m_raw.insert(m_raw.end(), cipher, cipher + len);
if (m_raw.empty())
return 0;
for (;;)
{
SecBuffer bufs[4] = {
{ (ULONG)m_raw.size(), SECBUFFER_DATA, m_raw.empty() ? NULL : 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; // 记录不完整,等下一轮 WSARecv
if (sc == SEC_I_CONTEXT_EXPIRED) {
Mprintf("[TLS] DecryptMessage: peer close_notify (SEC_I_CONTEXT_EXPIRED)\n");
return -1; // 对端 close_notify / 会话结束
}
if (sc == SEC_I_RENEGOTIATE || FAILED(sc)) {
Mprintf("[TLS] DecryptMessage failed 0x%08x (raw=%u)\n", (unsigned)sc, (unsigned)m_raw.size());
return -1;
}
int decLen = (int)bufs[1].cbBuffer;
const BYTE* p = (const BYTE*)bufs[1].pvBuffer;
int extra = (bufs[3].BufferType == SECBUFFER_EXTRA) ? (int)bufs[3].cbBuffer : 0;
int consumed = (int)m_raw.size() - extra;
if (decLen > 0 && p)
plain.insert(plain.end(), p, p + decLen);
m_raw.erase(m_raw.begin(), m_raw.begin() + consumed);
if (m_raw.empty())
break;
}
return 0;
}
int ServerTlsSession::Encrypt(const BYTE* plain, int len, std::vector<BYTE>& wire)
{
std::lock_guard<std::mutex> lk(m_mtx);
if (!m_ready)
return -1;
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, plain + 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 -1; // 握手已建立,此处失败视为致命(调用方关闭连接)
int wireLen = (int)(bufs[0].cbBuffer + bufs[1].cbBuffer + bufs[2].cbBuffer);
wire.insert(wire.end(), rec.data(), rec.data() + wireLen);
total += chunk;
}
return total;
}
// =====================================================================================
// CONTEXT_OBJECT::FreeTls —— 释放每连接 TLS 会话(定义在此以便 delete 完整类型)
// =====================================================================================
void CONTEXT_OBJECT::FreeTls()
{
delete tls;
tls = NULL;
}
// =====================================================================================
// 额外入站身份(MCP 等第二套证书)
// =====================================================================================
bool ServerTlsLoadIdentityFromPem(const std::string& certPath, const std::string& keyPath,
const wchar_t* keyName, ServerTlsExtraIdentity& out)
{
CredHandle cred = {};
PCCERT_CONTEXT cert = NULL;
NCRYPT_KEY_HANDLE key = 0;
if (!BuildIdentity(certPath, keyPath, keyName, cred, cert, key))
return false;
out.cred = cred;
out.cert = cert;
out.key = (ULONG_PTR)key;
return true;
}
void ServerTlsFreeIdentity(ServerTlsExtraIdentity& id)
{
// 顺序同 ServerTlsIdentity::FreeIdentity:凭据 → 证书 → 持久化私钥。
if (id.cred.dwLower || id.cred.dwUpper)
{
FreeCredentialsHandle(&id.cred);
id.cred = {};
}
if (id.cert)
{
CertFreeCertificateContext(id.cert);
id.cert = NULL;
}
if (id.key)
{
NCryptDeleteKey((NCRYPT_KEY_HANDLE)id.key, 0);
id.key = 0;
}
}