The built-in certificate lives only inside the server config as base64 DER, so there was no way to take it elsewhere -- to install it as a custom certificate on another machine, or to hand it to a proxy. The TLS certificate dialog now has an Export Certificate button next to the Built-in Certificate checkbox. It is enabled only while that box is checked. Clicking it opens a save dialog and writes two PEM files: the chosen .crt and a .key with the same base name in the same directory. The key is PKCS#8 and unencrypted; the success message says so. If the certificate has not been generated yet (box checked but the dialog not applied), the export generates it first, the same way OK does, then refreshes the expiry text. If the key cannot be written, the certificate written just before it is deleted, so no half pair is left. Translations added for en_US, zh_TW and de_DE; en_US and zh_TW are also embedded resources, so the server was rebuilt. Verified: Debug x64 server builds clean. Drove the dialog on a running Debug instance over window messages -- the button, its label and its enabled state track the checkbox. The PEM writer was checked against OpenSSL (x509 -subject, pkey -check) using the same CryptoAPI flags. The save dialog itself was not automated end to end. Co-Authored-By: deepseek-flash
323 lines
12 KiB
C++
323 lines
12 KiB
C++
#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();
|
||
}
|
||
|
||
// DER → PEM(64 列换行 + 自定义标签)。CRYPT_STRING_BASE64HEADER 只会写死
|
||
// "CERTIFICATE" 标签,私钥得自己包 "PRIVATE KEY"(与 PKCS#8 对应)。
|
||
std::string DerToPem(const std::vector<BYTE>& der, const char* label)
|
||
{
|
||
if (der.empty() || label == NULL)
|
||
return std::string();
|
||
|
||
DWORD chars = 0;
|
||
// CRYPT_STRING_BASE64:无头尾,按 64 列插入 CRLF(未带 NOCRLF 时)
|
||
if (!CryptBinaryToStringA(der.data(), (DWORD)der.size(), CRYPT_STRING_BASE64, NULL, &chars) || chars == 0)
|
||
return std::string();
|
||
|
||
std::vector<char> buf(chars, '\0');
|
||
if (!CryptBinaryToStringA(der.data(), (DWORD)der.size(), CRYPT_STRING_BASE64, buf.data(), &chars))
|
||
return std::string();
|
||
|
||
size_t n = chars;
|
||
while (n > 0 && buf[n - 1] == '\0')
|
||
--n;
|
||
std::string body(buf.data(), n);
|
||
if (body.empty())
|
||
return std::string();
|
||
if (body.back() != '\n')
|
||
body += "\r\n";
|
||
|
||
return std::string("-----BEGIN ") + label + "-----\r\n" + body +
|
||
"-----END " + label + "-----\r\n";
|
||
}
|
||
|
||
// 按天数平移 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);
|
||
}
|
||
|
||
bool BuiltinTlsCert::ExportPem(config& cfg, std::string& certPem, std::string& keyPem)
|
||
{
|
||
std::vector<BYTE> certDer, keyDer;
|
||
if (!ReadDer(cfg, certDer, keyDer))
|
||
return false;
|
||
|
||
certPem = DerToPem(certDer, "CERTIFICATE");
|
||
keyPem = DerToPem(keyDer, "PRIVATE KEY");
|
||
return !certPem.empty() && !keyPem.empty();
|
||
}
|
||
|
||
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;
|
||
}
|