Feature: Terminate TLS for the MCP endpoint inside YAMA

MCP was served by a plain httplib::Server, so remote clients could only use
cleartext HTTP. YAMA now terminates TLS itself: a small front-end owns the
MCP port, sniffs the first byte and either runs a Schannel handshake and
forwards the decrypted bytes or passes plaintext through, with httplib
moving to a loopback-only internal port. No OpenSSL, no frp change, existing
local HTTP clients keep working, and an unusable certificate fails closed
instead of falling back to cleartext.

The identity loader grew the two things a public certificate needs. ECDSA
(P-256/P-384/P-521) keys are persisted by importing PKCS#8 with an
NCRYPTBUFFER_PKCS_KEY_NAME parameter, the only route MS Software KSP
supports for Schannel; RSA keeps its old export-and-repersist path.
Fullchains are accepted, and the intermediates are added to the current
user's CA store so Schannel, which builds chains only from system stores,
actually sends them. The shared handshake also now buffers a full TLS
record before the first AcceptSecurityContext, which a partial ClientHello
would otherwise poison (SEC_E_UNKNOWN_CREDENTIALS).

Session resumption exposed a second trap: when a client resumes a session,
ChangeCipherSpec, Finished and the first application record arrive in one
segment and AcceptSecurityContext leaves the application record pending in
the session. Nothing drained it, because both callers only decrypt when new
ciphertext arrives, so the request waited until the peer gave up (the MCP
front-end saw no request at all and the client reported "fetch failed
(other side closed)"; the device port had the same hole behind its
occasional login timeouts). Decrypt now drains pending data on len == 0, and
both the front-end and the device port's handshake thread use it before
entering their receive loops.

Configuration is McpHttps, McpCertPath, McpKeyPath and McpInternalPort, the
first three editable in the MCP settings dialog (the certificate rows stay
greyed out until HTTPS is enabled and saving rejects missing files).

Verified with a real Let's Encrypt ECDSA fullchain (53 tools over TLS, 401
with no or bad token), a local three-level chain whose intermediate was
absent from the store, Node 24's fetch on a resumed session (initialize,
notifications/initialized and tools/list all complete), and the device
port's RSA handshake as a regression check. Details in docs/Mcp_Design.md
section 13.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-10-26 13:56:41 +01:00
1 parent b4cb34fea9
commit a7dd86ff0f
15 files changed
+1218 -96

No files matched your search

+332 -88
View File
@@ -75,6 +75,31 @@ KeyFmt DetectKeyFormat(const std::string& keyPem)
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;
}
}
// =====================================================================================
@@ -143,7 +168,35 @@ bool ServerTlsIdentity::Load(config& cfg)
return true;
}
bool ServerTlsIdentity::LoadIdentity(const std::string& certPath, const std::string& keyPath)
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);
}
// 按给定 PEM(证书链 + PKCS#8 私钥)与 CNG 持久化键名构造一份入站身份。
// 设备端口(ServerTlsIdentity,键名 YamaServerTlsKey)与 MCP 前端(独立键名)共用这段
// 逻辑;键名不同则两份身份可并存,互不覆盖。
// 成功时 outCred / outCert / outKey 均有效,生命周期由调用方释放。
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))
@@ -157,28 +210,100 @@ bool ServerTlsIdentity::LoadIdentity(const std::string& certPath, const std::str
return false;
}
// 1) 证书:PEM → DER → PCCERT_CONTEXT。
std::vector<BYTE> certDer;
if (!PemToDer(certPem, certDer))
// 1) 证书:PEM → DER → PCCERT_CONTEXT(第一块为叶证书)。
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;
}
PCCERT_CONTEXT cert = CertCreateCertificateContext(X509_ASN_ENCODING,
certDer.data(), (DWORD)certDer.size());
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, certPath.c_str(), 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, certPath.c_str(), GetLastError());
}
CertFreeCertificateContext(chainCert);
}
// 2) 私钥:PEM → DER → 持久化到 CNG KSP(仅支持 PKCS#8;PKCS#1 给出可操作的转换提示)。
//
// 关键:Schannel 入站凭据(AcquireCredentialsHandle)需要「能按名重开」的持久化私钥。
// NCryptImportKey 产出的是匿名临时键,绑定 CERT_NCRYPT_KEY_HANDLE_PROP_ID 后 Schannel 仍
// 拿不到(AcquireCredentialsHandle 返回 SEC_E_NO_CREDENTIALS 0x8009030e)。因此先把
// PKCS#8 导入为临时键、导出为裸 RSA 私钥 BLOB(NCryptSetProperty 只认裸 BLOB,不认
// PKCS#8),再写入持久化键并 finalize,最后用 CERT_KEY_PROV_INFO_PROP_ID 按名引用。
// 匿名临时键不行:绑定 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",
certPath.c_str(), 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",
certPath.c_str());
CertFreeCertificateContext(cert);
return false;
}
}
std::vector<BYTE> keyDer;
NCRYPT_KEY_HANDLE persistedKey = 0;
if (DetectKeyFormat(keyPem) == KF_PKCS8)
@@ -201,37 +326,67 @@ bool ServerTlsIdentity::LoadIdentity(const std::string& certPath, const std::str
return false;
}
// 2a) PKCS#8 → 临时键。
NCRYPT_KEY_HANDLE tmp = 0;
st = NCryptImportKey(hProv, NULL, NCRYPT_PKCS8_PRIVATE_KEY_BLOB, NULL,
&tmp, keyDer.data(), (DWORD)keyDer.size(), 0);
if (st == ERROR_SUCCESS)
// 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)
{
// 2b) 允许明文导出,导出为裸 RSA 私钥 BLOB。
DWORD policy = NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG | NCRYPT_ALLOW_EXPORT_FLAG;
NCryptSetProperty(tmp, NCRYPT_EXPORT_POLICY_PROPERTY, (PBYTE)&policy, sizeof(policy), 0);
std::wstring nameW(keyName);
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;
std::vector<BYTE> raw;
DWORD rawLen = 0;
st = NCryptExportKey(tmp, NULL, BCRYPT_RSAFULLPRIVATE_BLOB, NULL, NULL, 0, &rawLen, 0);
st = NCryptImportKey(hProv, NULL, NCRYPT_PKCS8_PRIVATE_KEY_BLOB, &desc,
&persistedKey, 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, keyDer.data(), (DWORD)keyDer.size(), 0);
if (st == ERROR_SUCCESS)
{
raw.resize(rawLen);
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,
raw.data(), rawLen, &rawLen, 0);
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,
keyName, 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);
}
// 2c) 写入持久化键并 finalize(落到 KSP,可被 Schannel 按名重开)。
if (st == ERROR_SUCCESS)
st = NCryptCreatePersistedKey(hProv, &persistedKey, BCRYPT_RSA_ALGORITHM,
g_keyName, 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);
@@ -257,54 +412,55 @@ bool ServerTlsIdentity::LoadIdentity(const std::string& certPath, const std::str
// 3) 绑定私钥到证书上下文:按名引用持久化键。Schannel 经 CryptAcquireCertificatePrivateKey
// 在 MS_KEY_STORAGE_PROVIDER 里用 pwszContainerName 重开该键。
// 4) 换入站凭据(单向 TLS,不请求客户端证书)。
CRYPT_KEY_PROV_INFO provInfo = {};
provInfo.pwszContainerName = (LPWSTR)g_keyName;
provInfo.pwszContainerName = (LPWSTR)keyName;
provInfo.pwszProvName = (LPWSTR)MS_KEY_STORAGE_PROVIDER;
provInfo.dwProvType = 0; // 0 = CNG(无 CAPI provider type)
provInfo.dwKeySpec = AT_KEYEXCHANGE;
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 (%u)\n", GetLastError());
NCryptDeleteKey(persistedKey, 0); // 删除并释放句柄
CertFreeCertificateContext(cert);
return false;
"failed 0x%08x\n", (unsigned)st);
}
else
{
st = AcquireInboundCredFor(cert, cred);
}
// 绑定后持久化键句柄交进程级 g_persistedKey,随 FreeIdentity 删除(覆盖旧键,避免残留)。
g_persistedKey = persistedKey;
// 4) 入站凭据:显式指定服务端证书,不请求客户端证书(单向 TLS)。
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;
TimeStamp tsExpiry = {};
SECURITY_STATUS st = AcquireCredentialsHandleA(
NULL, (SEC_CHAR*)"Microsoft Unified Security Protocol Provider", SECPKG_CRED_INBOUND,
NULL, &sc, NULL, NULL, &g_cred, &tsExpiry);
if (st != SEC_E_OK)
{
Mprintf("[TLS] FATAL: AcquireCredentialsHandle(SECPKG_CRED_INBOUND) failed 0x%08x\n",
(unsigned)st);
CertFreeCertificateContext(cert); // 无凭据引用,安全释放
g_cred = {};
if (g_persistedKey) // 回滚:删除已持久化的私钥,避免残留
{
NCryptDeleteKey(g_persistedKey, 0); // 删除并释放句柄
g_persistedKey = 0;
}
NCryptDeleteKey(persistedKey, 0); // 回滚:删除已持久化的私钥,避免残留
return false;
}
outCert = cert;
outKey = persistedKey;
outCred = cred;
return 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;
// 成功:把证书上下文生命周期交给进程级 g_cert,随 FreeIdentity 释放,
// 保证在 FreeCredentialsHandle 之前私钥一直可用。
g_cred = cred;
g_cert = cert;
g_persistedKey = key;
g_credValid = true;
return true;
}
@@ -385,25 +541,89 @@ bool ServerTlsSession::SendAll(SOCKET sock, const void* data, int len)
}
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(); // 防御:会话应只握手一次
CredHandle cred = ServerTlsIdentity::Cred();
// 单向 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(initial, initial + initialLen);
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] = {
@@ -454,29 +674,11 @@ bool ServerTlsSession::Handshake(SOCKET sock, const BYTE* initial, int initialLe
break; // 真正的失败
}
char raw[8192];
int r;
for (;;)
if (!RecvMore(hs))
{
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());
sc = SEC_E_INTERNAL_ERROR;
break;
}
hs.insert(hs.end(), (BYTE*)raw, (BYTE*)raw + r);
}
if (sc != SEC_E_OK)
@@ -512,11 +714,14 @@ int ServerTlsSession::Decrypt(const BYTE* cipher, int len, std::vector<BYTE>& pl
std::lock_guard<std::mutex> lk(m_mtx);
if (!m_ready)
return -1;
if (len <= 0)
// len == 0 表示「只取残留」:握手结束时会话里可能已经躺着紧随 Finished 的首条
// 应用数据(见 HandshakeWithCred 末尾),调用方必须在进入收发循环前取一次,
// 否则这份数据要等下一条密文到达才会被解出来。
if (len > 0)
m_raw.insert(m_raw.end(), cipher, cipher + len);
if (m_raw.empty())
return 0;
m_raw.insert(m_raw.end(), cipher, cipher + len);
for (;;)
{
SecBuffer bufs[4] = {
@@ -602,3 +807,42 @@ 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;
}
}