94a0e255aa
Settings › Server Certificate stores a binding in the database (tls.serverCertificate): the certificate's subject, issuer, DNS names and template plus the thumbprint bound, never just a thumbprint. Every minute each replica picks what to serve from its own LocalMachine\My: Windows' renewal link first, otherwise the newest usable certificate with the same template (else issuer) and the same subject or DNS name set; the swap needs no restart and each replica records what it serves and when it last switched. The managed self-signed chain can be bound too; clearing the binding serves the configured source again. A certificate setting in the process environment wins over the binding; appsettings.json (what setup writes) is the default it replaces. A new private root after a switch is recorded (tls.rootChange) for the console. GET/POST/DELETE /api/settings/server-certificate*, settings.manage, audited. Context creation now fails soft when Windows' chain engine errors. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
110 lines
5.6 KiB
C#
110 lines
5.6 KiB
C#
using System.Net;
|
|
using System.Security.Cryptography;
|
|
using System.Security.Cryptography.X509Certificates;
|
|
|
|
namespace Backend.Tests;
|
|
|
|
/// <summary>A private CA (root > intermediate) issuing TLS server leaves, as an enterprise PKI would.</summary>
|
|
internal sealed class TestPki : IDisposable
|
|
{
|
|
public TestPki(string name = "Test Enterprise")
|
|
{
|
|
var now = DateTimeOffset.UtcNow;
|
|
using var rootKey = RSA.Create(2048);
|
|
var rootRequest = new CertificateRequest($"CN={name} Root CA", rootKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
|
rootRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
|
|
rootRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, true));
|
|
rootRequest.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(rootRequest.PublicKey, false));
|
|
Root = rootRequest.CreateSelfSigned(now.AddYears(-2), now.AddYears(10));
|
|
|
|
using var intermediateKey = RSA.Create(2048);
|
|
var intermediateRequest = new CertificateRequest($"CN={name} Issuing CA", intermediateKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
|
intermediateRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, true, 0, true));
|
|
intermediateRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, true));
|
|
intermediateRequest.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(intermediateRequest.PublicKey, false));
|
|
intermediateRequest.CertificateExtensions.Add(X509AuthorityKeyIdentifierExtension.CreateFromCertificate(Root, true, false));
|
|
using var issued = intermediateRequest.Create(Root, now.AddYears(-1), now.AddYears(5), Serial());
|
|
Intermediate = issued.CopyWithPrivateKey(intermediateKey);
|
|
}
|
|
|
|
public X509Certificate2 Root { get; }
|
|
|
|
public X509Certificate2 Intermediate { get; }
|
|
|
|
public string RootFingerprint => Convert.ToHexStringLower(SHA256.HashData(Root.PublicKey.ExportSubjectPublicKeyInfo()));
|
|
|
|
/// <summary>A server leaf for localhost/127.0.0.1 with its private key.</summary>
|
|
/// <param name="dnsNames">DNS SANs (default localhost).</param>
|
|
/// <param name="template">A certificate template OID, stamped as an enterprise CA does.</param>
|
|
/// <param name="age">How long ago it was issued.</param>
|
|
/// <param name="eku">Its Enhanced Key Usage (default server authentication).</param>
|
|
public X509Certificate2 IssueLeaf(string subject = "CN=executer.test.local", int days = 90, string[]? dnsNames = null, string? template = null,
|
|
TimeSpan? age = null, string eku = "1.3.6.1.5.5.7.3.1")
|
|
{
|
|
var now = DateTimeOffset.UtcNow;
|
|
using var key = RSA.Create(2048);
|
|
var request = new CertificateRequest(subject, key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
|
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true));
|
|
request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment, true));
|
|
request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension([new Oid(eku)], false));
|
|
var san = new SubjectAlternativeNameBuilder();
|
|
foreach (var name in dnsNames ?? ["localhost"])
|
|
{
|
|
san.AddDnsName(name);
|
|
}
|
|
|
|
san.AddIpAddress(IPAddress.Loopback);
|
|
request.CertificateExtensions.Add(san.Build());
|
|
request.CertificateExtensions.Add(X509AuthorityKeyIdentifierExtension.CreateFromCertificate(Intermediate, true, false));
|
|
if (template is not null)
|
|
{
|
|
var writer = new System.Formats.Asn1.AsnWriter(System.Formats.Asn1.AsnEncodingRules.DER);
|
|
using (writer.PushSequence())
|
|
{
|
|
writer.WriteObjectIdentifier(template);
|
|
writer.WriteInteger(100);
|
|
writer.WriteInteger(4);
|
|
}
|
|
|
|
request.CertificateExtensions.Add(new X509Extension("1.3.6.1.4.1.311.21.7", writer.Encode(), false));
|
|
}
|
|
|
|
var issuedAt = now - (age ?? TimeSpan.FromMinutes(5));
|
|
using var issued = request.Create(Intermediate, issuedAt, issuedAt.AddDays(days), Serial());
|
|
return issued.CopyWithPrivateKey(key);
|
|
}
|
|
|
|
/// <summary>The leaf, intermediate and root in one password-protected PFX, as a CA export gives it.</summary>
|
|
public void WritePfx(string path, X509Certificate2 leaf, string password)
|
|
{
|
|
X509Certificate2Collection bundle =
|
|
[
|
|
leaf,
|
|
X509CertificateLoader.LoadCertificate(Intermediate.RawData),
|
|
X509CertificateLoader.LoadCertificate(Root.RawData),
|
|
];
|
|
File.WriteAllBytes(path, bundle.Export(X509ContentType.Pkcs12, password)!);
|
|
}
|
|
|
|
/// <summary>fullchain.pem (leaf, intermediate, root) and a separate key, as certbot or an ACME client lays them out.</summary>
|
|
public void WritePem(string certificatePath, string keyPath, X509Certificate2 leaf)
|
|
{
|
|
File.WriteAllText(certificatePath, leaf.ExportCertificatePem() + "\n" + Intermediate.ExportCertificatePem() + "\n" + Root.ExportCertificatePem() + "\n");
|
|
File.WriteAllText(keyPath, leaf.GetRSAPrivateKey()!.ExportPkcs8PrivateKeyPem());
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
ImportedCertificates.Remove(Intermediate);
|
|
Root.Dispose();
|
|
Intermediate.Dispose();
|
|
}
|
|
|
|
private static byte[] Serial()
|
|
{
|
|
var serial = RandomNumberGenerator.GetBytes(16);
|
|
serial[0] &= 0x7F;
|
|
return serial;
|
|
}
|
|
}
|