Files
SimpleRemoter/server/2015Remote/BuiltinTlsCert.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

283 lines
10 KiB
C++
Raw 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.
#include "stdafx.h"
#include "BuiltinTlsCert.h"
#include "common/iniFile.h" // config / iniFile(GetStr/SetStr/GetInt)
#include <ncrypt.h>
#include <wincrypt.h>
#pragma comment(lib, "ncrypt.lib")
#pragma comment(lib, "crypt32.lib")
namespace {
const char* kCertValue = "BuiltinCert"; // [tls] 单行 base64(DER 证书)
const char* kKeyValue = "BuiltinKey"; // [tls] 单行 base64(PKCS#8 DER 私钥)
// 生成期间用的 CNG 持久化键名:导出 PKCS#8 后立刻删除,不留在系统里(真正的私钥
// 存在配置里,由 ServerTlsSession 按需导入成 KSP 持久化键「YamaServerTlsKey-<指纹>」)。
const wchar_t* kGenKeyName = L"YamaBuiltinTlsKeyGen";
// 注意导出类型用 NCRYPT_PKCS8_PRIVATE_KEY_BLOB(L"PKCS8_PRIVATEKEY"),与导入侧
// (ServerTlsSession 的 NCryptImportKey) 完全对称。不要改成文献里常见的
// NCRYPT_PKCS8_PRIV_KEY_INFO_BLOB(L"PKCS8_PRIV_KEY_INFO"):Microsoft Software KSP
// 不支持它,实测返回 NTE_INVALID_PARAMETER(0x80090027),且本 SDK 的 ncrypt.h 也没这个宏。
// base64 编码(单行,无换行):INI 后端的值不能含换行,统一用无换行形式。
std::string EncodeB64(const BYTE* data, DWORD len)
{
DWORD chars = 0;
if (!CryptBinaryToStringA(data, len, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, NULL, &chars) || chars == 0)
return std::string();
std::vector<char> buf(chars, '\0');
if (!CryptBinaryToStringA(data, len, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, buf.data(), &chars))
return std::string();
// 去掉可能的末尾 '\0'
size_t n = chars;
while (n > 0 && buf[n - 1] == '\0')
--n;
return std::string(buf.data(), n);
}
bool DecodeB64(const std::string& b64, std::vector<BYTE>& der)
{
if (b64.empty())
return false;
DWORD len = 0;
if (!CryptStringToBinaryA(b64.data(), (DWORD)b64.size(), CRYPT_STRING_BASE64, NULL, &len, NULL, NULL) || len == 0)
return false;
der.resize(len);
if (!CryptStringToBinaryA(b64.data(), (DWORD)b64.size(), CRYPT_STRING_BASE64, der.data(), &len, NULL, NULL))
return false;
der.resize(len);
return !der.empty();
}
// 按天数平移 SYSTEMTIME(不能用 wYear += 10:遇上 2 月 29 会得到非法日期)。
void ShiftDays(const SYSTEMTIME& in, LONGLONG days, SYSTEMTIME& out)
{
FILETIME ft = {};
if (!SystemTimeToFileTime(&in, &ft)) {
out = in;
return;
}
ULARGE_INTEGER u;
u.LowPart = ft.dwLowDateTime;
u.HighPart = ft.dwHighDateTime;
u.QuadPart += (ULONGLONG)days * 86400ULL * 10000000ULL;
ft.dwLowDateTime = u.LowPart;
ft.dwHighDateTime = u.HighPart;
if (!FileTimeToSystemTime(&ft, &out))
out = in;
}
// 生成一对自签证书 + PKCS#8 私钥(均为单行 base64 的 DER)。
// 参数选择对齐 docs/TransportTLS_Design.md §9.1 的 `openssl req -x509`:
// RSA-2048、SHA-256、CN=yama-server、CA:TRUE、10 年有效期(提前 1 天生效,容时钟偏差)。
bool GenerateBlobs(std::string& certB64, std::string& keyB64)
{
NCRYPT_PROV_HANDLE hProv = 0;
SECURITY_STATUS st = NCryptOpenStorageProvider(&hProv, MS_KEY_STORAGE_PROVIDER, 0);
if (st != ERROR_SUCCESS) {
Mprintf("[TLS] builtin cert: NCryptOpenStorageProvider failed 0x%08x\n", (unsigned)st);
return false;
}
NCRYPT_KEY_HANDLE hKey = 0;
st = NCryptCreatePersistedKey(hProv, &hKey, NCRYPT_RSA_ALGORITHM, kGenKeyName, 0,
NCRYPT_OVERWRITE_KEY_FLAG);
if (st == ERROR_SUCCESS) {
DWORD bits = 2048;
st = NCryptSetProperty(hKey, NCRYPT_LENGTH_PROPERTY, (PBYTE)&bits, sizeof(bits), 0);
}
if (st == ERROR_SUCCESS) {
// 私钥要以 PKCS#8 导出后存进配置,故必须允许导出。
DWORD policy = NCRYPT_ALLOW_EXPORT_FLAG | NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG;
st = NCryptSetProperty(hKey, NCRYPT_EXPORT_POLICY_PROPERTY, (PBYTE)&policy, sizeof(policy), 0);
}
if (st == ERROR_SUCCESS)
st = NCryptFinalizeKey(hKey, 0);
if (st != ERROR_SUCCESS) {
Mprintf("[TLS] builtin cert: RSA-2048 key creation failed 0x%08x\n", (unsigned)st);
if (hKey)
NCryptFreeObject(hKey);
NCryptFreeObject(hProv);
return false;
}
// 主体:CN=yama-server
CERT_NAME_BLOB subject = {};
DWORD cbName = 0;
bool ok = CertStrToNameW(X509_ASN_ENCODING, L"CN=yama-server", CERT_X500_NAME_STR,
NULL, NULL, &cbName, NULL) != FALSE;
std::vector<BYTE> nameBuf;
if (ok) {
nameBuf.resize(cbName);
subject.pbData = nameBuf.data();
subject.cbData = cbName;
ok = CertStrToNameW(X509_ASN_ENCODING, L"CN=yama-server", CERT_X500_NAME_STR,
NULL, subject.pbData, &cbName, NULL) != FALSE;
subject.cbData = cbName;
}
if (!ok) {
Mprintf("[TLS] builtin cert: failed to encode subject name (%u)\n", GetLastError());
NCryptDeleteKey(hKey, 0);
NCryptFreeObject(hProv);
return false;
}
// BasicConstraints: cA=TRUE → DER: 30 03 01 01 FF
// 客户端用「只信任锚」的独占根链引擎校验,CA:TRUE 让这张自签证书干净地充当根,
// 避免 CERT_TRUST_INVALID_BASIC_CONSTRAINTS。
BYTE bcValue[] = { 0x30, 0x03, 0x01, 0x01, 0xFF };
CERT_EXTENSION ext = {};
ext.pszObjId = (LPSTR)szOID_BASIC_CONSTRAINTS2;
ext.fCritical = TRUE;
ext.Value.cbData = sizeof(bcValue);
ext.Value.pbData = bcValue;
CERT_EXTENSIONS exts = {};
exts.cExtension = 1;
exts.rgExtension = &ext;
CRYPT_ALGORITHM_IDENTIFIER sigAlg = {};
sigAlg.pszObjId = (LPSTR)szOID_RSA_SHA256RSA;
SYSTEMTIME now = {};
GetSystemTime(&now);
SYSTEMTIME startTime = {}, endTime = {};
ShiftDays(now, -1, startTime); // 提前 1 天生效,容两端时钟偏差
ShiftDays(now, 3650, endTime); // 10 年
// 直接把 CNG 私钥句柄交给 CertCreateSelfSignCertificate 签名(它的形参类型就是
// HCRYPTPROV_OR_NCRYPT_KEY_HANDLE),省去 CRYPT_KEY_PROV_INFO 的按名引用。
PCCERT_CONTEXT pCert = CertCreateSelfSignCertificate(
(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE)hKey, &subject, 0, NULL, &sigAlg,
&startTime, &endTime, &exts);
if (pCert == NULL) {
Mprintf("[TLS] builtin cert: CertCreateSelfSignCertificate failed (%u)\n", GetLastError());
NCryptDeleteKey(hKey, 0);
NCryptFreeObject(hProv);
return false;
}
certB64 = EncodeB64(pCert->pbCertEncoded, pCert->cbCertEncoded);
CertFreeCertificateContext(pCert);
// 私钥:PKCS#8 DER → base64。与用户自定义证书走同一条导入路径(ServerTlsSession
// 的 BuildIdentityFromDer 只认 PKCS#8)。
DWORD cbKey = 0;
st = NCryptExportKey(hKey, 0, NCRYPT_PKCS8_PRIVATE_KEY_BLOB, NULL, NULL, 0, &cbKey, 0);
std::vector<BYTE> keyDer;
if (st == ERROR_SUCCESS && cbKey > 0) {
keyDer.resize(cbKey);
st = NCryptExportKey(hKey, 0, NCRYPT_PKCS8_PRIVATE_KEY_BLOB, NULL,
keyDer.data(), cbKey, &cbKey, 0);
}
if (st != ERROR_SUCCESS || cbKey == 0) {
Mprintf("[TLS] builtin cert: NCryptExportKey(PKCS#8) failed 0x%08x\n", (unsigned)st);
NCryptDeleteKey(hKey, 0);
NCryptFreeObject(hProv);
return false;
}
keyDer.resize(cbKey);
keyB64 = EncodeB64(keyDer.data(), (DWORD)keyDer.size());
// 生成用键只活在本次调用里,立刻删掉,避免在 KSP 里留一份私钥。
NCryptDeleteKey(hKey, 0);
NCryptFreeObject(hProv);
if (certB64.empty() || keyB64.empty()) {
Mprintf("[TLS] builtin cert: base64 encoding failed\n");
return false;
}
return true;
}
} // namespace
bool BuiltinTlsCert::UseBuiltin(config& cfg)
{
// 显式键优先;未设置时按「有自定义证书路径就不用内置」推导——老部署一定填了
// CertPath/KeyPath,升级后保持原样;全新部署两项都空,自动落到内置证书。
int v = cfg.GetInt("tls", "UseBuiltIn", -1);
if (v >= 0)
return v != 0;
return cfg.GetStr("tls", "CertPath", "").empty() &&
cfg.GetStr("tls", "KeyPath", "").empty();
}
bool BuiltinTlsCert::ReadDer(config& cfg, std::vector<BYTE>& certDer, std::vector<BYTE>& keyDer)
{
return DecodeB64(cfg.GetStr("tls", kCertValue, ""), certDer) &&
DecodeB64(cfg.GetStr("tls", kKeyValue, ""), keyDer);
}
bool BuiltinTlsCert::Ensure(config& cfg)
{
std::vector<BYTE> certDer, keyDer;
if (ReadDer(cfg, certDer, keyDer))
return true;
std::string certB64, keyB64;
if (!GenerateBlobs(certB64, keyB64))
return false;
if (!cfg.SetStr("tls", kCertValue, certB64) || !cfg.SetStr("tls", kKeyValue, keyB64)) {
Mprintf("[TLS] builtin cert: failed to persist certificate/key into config\n");
return false;
}
return ReadDer(cfg, certDer, keyDer);
}
std::string BuiltinTlsCert::CertPem(config& cfg)
{
std::vector<BYTE> certDer, keyDer;
if (!ReadDer(cfg, certDer, keyDer))
return std::string();
// CRYPT_STRING_BASE64HEADER 直接产出标准 PEM(头尾行 + 64 列换行),
// 客户端与 Linux 端的信任锚文件都吃这种格式。
DWORD chars = 0;
if (!CryptBinaryToStringA(certDer.data(), (DWORD)certDer.size(), CRYPT_STRING_BASE64HEADER, NULL, &chars) || chars == 0)
return std::string();
std::vector<char> buf(chars, '\0');
if (!CryptBinaryToStringA(certDer.data(), (DWORD)certDer.size(), CRYPT_STRING_BASE64HEADER, buf.data(), &chars))
return std::string();
size_t n = chars;
while (n > 0 && buf[n - 1] == '\0')
--n;
return std::string(buf.data(), n);
}
std::string BuiltinTlsCert::Describe(config& cfg)
{
std::vector<BYTE> certDer, keyDer;
if (!ReadDer(cfg, certDer, keyDer))
return std::string();
PCCERT_CONTEXT cert = CertCreateCertificateContext(
X509_ASN_ENCODING, certDer.data(), (DWORD)certDer.size());
if (cert == NULL)
return std::string();
// CERT_INFO 的 NotAfter 是 FILETIME,转成 SYSTEMTIME 才好取年月日。
SYSTEMTIME na = {};
if (!FileTimeToSystemTime(&cert->pCertInfo->NotAfter, &na)) {
CertFreeCertificateContext(cert);
return std::string();
}
char text[32] = { 0 };
sprintf_s(text, "%04u-%02u-%02u", na.wYear, na.wMonth, na.wDay);
CertFreeCertificateContext(cert);
return text;
}