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
This commit is contained in:
1 parent
4f9bfb0fdc
commit
c4021e1fc9
16 files changed
+697
-131
No files matched your search
@@ -5,6 +5,7 @@
|
||||
// 以便与 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)
|
||||
|
||||
@@ -26,13 +27,16 @@ 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 中的名字。用固定名 + NCRYPT_OVERWRITE_KEY_FLAG,重启时覆盖旧键,
|
||||
// 避免残留;同名键的密钥材料与 server.key 相同,覆盖无副作用。
|
||||
// 持久化私钥在 CNG KSP 中的名字基名。实际键名还会拼上证书指纹(见
|
||||
// BuildIdentityFromDer),所以换证书不会撞名;同一张证书始终对应同一个键,
|
||||
// 配合 NCRYPT_OVERWRITE_KEY_FLAG 重启时覆盖旧键,避免残留。
|
||||
const wchar_t* g_keyName = L"YamaServerTlsKey";
|
||||
|
||||
// 一次性读文件为 std::string(二进制安全)。
|
||||
@@ -131,7 +135,10 @@ bool ServerTlsIdentity::Load(config& cfg)
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_identityMtx);
|
||||
|
||||
bool enabled = cfg.GetInt("tls", "Enabled", 0) != 0;
|
||||
// 缺省启用:全新部署没有 [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", "");
|
||||
|
||||
@@ -142,6 +149,8 @@ bool ServerTlsIdentity::Load(config& cfg)
|
||||
FreeIdentity();
|
||||
g_ready = false;
|
||||
g_loadError = false;
|
||||
g_builtin = false;
|
||||
g_anchorPem.clear();
|
||||
|
||||
if (!enabled)
|
||||
{
|
||||
@@ -149,6 +158,29 @@ bool ServerTlsIdentity::Load(config& cfg)
|
||||
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;
|
||||
@@ -163,6 +195,10 @@ bool ServerTlsIdentity::Load(config& cfg)
|
||||
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;
|
||||
@@ -190,33 +226,23 @@ SECURITY_STATUS AcquireInboundCredFor(PCCERT_CONTEXT cert, CredHandle& cred)
|
||||
NULL, &sc, NULL, NULL, &cred, &tsExpiry);
|
||||
}
|
||||
|
||||
// 按给定 PEM(证书链 + PKCS#8 私钥)与 CNG 持久化键名构造一份入站身份。
|
||||
// 设备端口(ServerTlsIdentity,键名 YamaServerTlsKey)与 MCP 前端(独立键名)共用这段
|
||||
// 逻辑;键名不同则两份身份可并存,互不覆盖。
|
||||
// 按「DER 证书链 + PKCS#8 私钥 DER」与 CNG 持久化键名构造一份入站身份。
|
||||
// 文件证书(BuildIdentity)、内置证书(BuiltinTlsCert)与 MCP 前端(独立键名)共用这段
|
||||
// 逻辑;键名不同则多份身份可并存,互不覆盖。source 仅用于日志定位。
|
||||
// 成功时 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)
|
||||
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)
|
||||
{
|
||||
std::string certPem, keyPem;
|
||||
if (!ReadFileText(certPath, certPem))
|
||||
if (certDers.empty())
|
||||
{
|
||||
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());
|
||||
Mprintf("[TLS] FATAL: empty certificate for %s\n", source ? source : "?");
|
||||
return false;
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
// 1) 证书:DER → PCCERT_CONTEXT(第一块为叶证书)。
|
||||
PCCERT_CONTEXT cert = CertCreateCertificateContext(X509_ASN_ENCODING,
|
||||
certDers[0].data(), (DWORD)certDers[0].size());
|
||||
if (cert == NULL)
|
||||
@@ -237,7 +263,7 @@ bool BuildIdentity(const std::string& certPath, const std::string& keyPath,
|
||||
{
|
||||
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());
|
||||
(unsigned)i, source ? source : "?", GetLastError());
|
||||
continue;
|
||||
}
|
||||
static HCERTSTORE s_caStore = NULL; // 进程级;关掉反而让 Schannel 后续取不到
|
||||
@@ -255,12 +281,45 @@ bool BuildIdentity(const std::string& certPath, const std::string& keyPath,
|
||||
{
|
||||
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());
|
||||
(unsigned)i, source ? source : "?", GetLastError());
|
||||
}
|
||||
CertFreeCertificateContext(chainCert);
|
||||
}
|
||||
|
||||
// 2) 私钥:PEM → DER → 持久化到 CNG KSP(仅支持 PKCS#8;PKCS#1 给出可操作的转换提示)。
|
||||
// 持久化键名 = 调用方给的基名 + 证书指纹前缀。
|
||||
//
|
||||
// 为什么不能只用固定键名:私钥是按名绑到证书上的(下面的 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
|
||||
@@ -278,7 +337,7 @@ bool BuildIdentity(const std::string& certPath, const std::string& keyPath,
|
||||
{
|
||||
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");
|
||||
source ? source : "?", certKeyOid ? certKeyOid : "unknown");
|
||||
CertFreeCertificateContext(cert);
|
||||
return false;
|
||||
}
|
||||
@@ -299,21 +358,14 @@ bool BuildIdentity(const std::string& certPath, const std::string& keyPath,
|
||||
{
|
||||
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());
|
||||
source ? source : "?");
|
||||
CertFreeCertificateContext(cert);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
std::vector<BYTE> keyDer;
|
||||
NCRYPT_KEY_HANDLE persistedKey = 0;
|
||||
if (DetectKeyFormat(keyPem) == KF_PKCS8)
|
||||
if (!keyDer.empty())
|
||||
{
|
||||
if (!PemToDer(keyPem, keyDer))
|
||||
{
|
||||
Mprintf("[TLS] FATAL: key file %s is not a valid PEM\n", keyPath.c_str());
|
||||
CertFreeCertificateContext(cert);
|
||||
return false;
|
||||
}
|
||||
// 显式打开 Microsoft Software Key Storage Provider。hProvider 传 NULL 会让
|
||||
// NCryptImportKey 走「默认提供者」解析,实测返回 NTE_INVALID_HANDLE(0x80090026),
|
||||
// 故必须显式取得 KSP 句柄(临时键独立于 hProv,导入后即可释放)。
|
||||
@@ -336,7 +388,7 @@ bool BuildIdentity(const std::string& certPath, const std::string& keyPath,
|
||||
// PKCS#8)→ 写入持久化键 → finalize。
|
||||
if (certKeyIsEc)
|
||||
{
|
||||
std::wstring nameW(keyName);
|
||||
std::wstring nameW(effectiveKeyName);
|
||||
NCryptBuffer nameBuf = {};
|
||||
nameBuf.cbBuffer = (ULONG)((nameW.size() + 1) * sizeof(WCHAR));
|
||||
nameBuf.BufferType = NCRYPTBUFFER_PKCS_KEY_NAME;
|
||||
@@ -347,14 +399,14 @@ bool BuildIdentity(const std::string& certPath, const std::string& keyPath,
|
||||
desc.pBuffers = &nameBuf;
|
||||
|
||||
st = NCryptImportKey(hProv, NULL, NCRYPT_PKCS8_PRIVATE_KEY_BLOB, &desc,
|
||||
&persistedKey, keyDer.data(), (DWORD)keyDer.size(),
|
||||
&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, keyDer.data(), (DWORD)keyDer.size(), 0);
|
||||
&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;
|
||||
@@ -374,7 +426,7 @@ bool BuildIdentity(const std::string& certPath, const std::string& keyPath,
|
||||
if (st == ERROR_SUCCESS)
|
||||
{
|
||||
st = NCryptCreatePersistedKey(hProv, &persistedKey, BCRYPT_RSA_ALGORITHM,
|
||||
keyName, AT_KEYEXCHANGE,
|
||||
effectiveKeyName.c_str(), AT_KEYEXCHANGE,
|
||||
NCRYPT_OVERWRITE_KEY_FLAG);
|
||||
}
|
||||
if (st == ERROR_SUCCESS)
|
||||
@@ -393,7 +445,7 @@ bool BuildIdentity(const std::string& certPath, const std::string& keyPath,
|
||||
if (st != ERROR_SUCCESS)
|
||||
{
|
||||
Mprintf("[TLS] FATAL: failed to persist PKCS#8 key for %s (0x%08x)\n",
|
||||
keyPath.c_str(), (unsigned)st);
|
||||
source ? source : "?", (unsigned)st);
|
||||
if (persistedKey)
|
||||
NCryptFreeObject(persistedKey);
|
||||
CertFreeCertificateContext(cert);
|
||||
@@ -402,10 +454,7 @@ bool BuildIdentity(const std::string& certPath, const std::string& keyPath,
|
||||
}
|
||||
else
|
||||
{
|
||||
// PKCS#1(RSA/EC PRIVATE KEY)或未知格式:本次不支持,给转换命令。
|
||||
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());
|
||||
Mprintf("[TLS] FATAL: empty private key for %s\n", source ? source : "?");
|
||||
CertFreeCertificateContext(cert);
|
||||
return false;
|
||||
}
|
||||
@@ -414,7 +463,7 @@ bool BuildIdentity(const std::string& certPath, const std::string& keyPath,
|
||||
// 在 MS_KEY_STORAGE_PROVIDER 里用 pwszContainerName 重开该键。
|
||||
// 4) 换入站凭据(单向 TLS,不请求客户端证书)。
|
||||
CRYPT_KEY_PROV_INFO provInfo = {};
|
||||
provInfo.pwszContainerName = (LPWSTR)keyName;
|
||||
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
|
||||
@@ -441,11 +490,68 @@ bool BuildIdentity(const std::string& certPath, const std::string& keyPath,
|
||||
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)
|
||||
@@ -456,12 +562,21 @@ bool ServerTlsIdentity::LoadIdentity(const std::string& certPath, const std::str
|
||||
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;
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -483,12 +598,27 @@ bool ServerTlsIdentity::IsLoadError()
|
||||
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 —— 单连接会话(握手 + 加解密)
|
||||
// =====================================================================================
|
||||
|
||||
Reference in new issue
Block a user