Files
Chronos/src/Titano.Server/Hosting/CertificateStore.cs
T
Claude c40b6a7cd3 feat: Phase 0 shells, design system, server skeleton, Docker and CI
- Titano.Ui: DESIGN.md tokens (dark/light), generated 16-px icon set,
  styles for all standard controls, custom chrome window with snap
  layouts, rail, job bar, Auto/manual slider, chips, toasts.
- Titano desktop shell with sections, Settings (language, theme),
  About and a --capture screenshot mode.
- Titano Server skeleton: env/server.json configuration, self-signed
  TLS with fingerprint, /health, /server/info, i18n endpoint and the
  embedded admin panel; in-process server tests.
- Docker image (multi-arch, PUID/PGID, health check), compose file,
  Unraid template; CI, release and nightly workflows; changelog tool.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-02 09:35:03 +00:00

80 lines
4.1 KiB
C#

using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Titano.Server.Configuration;
namespace Titano.Server.Hosting;
/// <summary>
/// TLS certificate for Kestrel (BRIEF §14.2): self-signed ECDSA P-256 generated once and kept in /data/tls
/// (mode auto), loaded from PEM files (mode pem), or none (mode proxy).
/// </summary>
public static class CertificateStore
{
public static X509Certificate2? Load(ServerOptions options, ILogger logger)
{
switch (options.TlsMode)
{
case TlsMode.Proxy:
return null;
case TlsMode.Pem:
{
var pem = X509Certificate2.CreateFromPemFile(options.TlsCert!, options.TlsKey);
return Exportable(pem);
}
default:
{
Directory.CreateDirectory(options.TlsPath);
var path = Path.Combine(options.TlsPath, "server.pfx");
if (File.Exists(path))
{
var existing = X509CertificateLoader.LoadPkcs12FromFile(path, password: null, X509KeyStorageFlags.Exportable);
if (existing.NotAfter > DateTime.UtcNow.AddDays(30)) return existing;
logger.LogWarning("Self-signed certificate expires {NotAfter:u}; generating a new one (clients will see a new fingerprint).", existing.NotAfter);
}
var created = CreateSelfSigned(options.ServerName);
File.WriteAllBytes(path, created.Export(X509ContentType.Pkcs12));
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite);
logger.LogInformation("Generated self-signed TLS certificate, SHA-256 fingerprint {Fingerprint}", Fingerprint(created));
return created;
}
}
}
/// <summary>SHA-256 fingerprint as colon-separated upper-case hex, as shown to users for trust-on-first-use.</summary>
public static string Fingerprint(X509Certificate2 certificate) =>
string.Join(':', certificate.GetCertHash(HashAlgorithmName.SHA256).Select(b => b.ToString("X2", System.Globalization.CultureInfo.InvariantCulture)));
public static X509Certificate2 CreateSelfSigned(string serverName)
{
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
var request = new CertificateRequest(new X500DistinguishedName($"CN={Sanitize(serverName)}, O=Titano"), key, HashAlgorithmName.SHA256);
var san = new SubjectAlternativeNameBuilder();
san.AddDnsName("localhost");
try
{
var host = Dns.GetHostName();
san.AddDnsName(host);
foreach (var address in Dns.GetHostAddresses(host).Where(a => a.AddressFamily is AddressFamily.InterNetwork or AddressFamily.InterNetworkV6))
san.AddIpAddress(address);
}
catch (SocketException)
{
// Without name resolution the certificate still covers localhost.
}
san.AddIpAddress(IPAddress.Loopback);
request.CertificateExtensions.Add(san.Build());
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true));
request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, true));
request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension([new Oid("1.3.6.1.5.5.7.3.1")], false));
using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(5));
return Exportable(certificate);
}
private static X509Certificate2 Exportable(X509Certificate2 certificate) =>
X509CertificateLoader.LoadPkcs12(certificate.Export(X509ContentType.Pkcs12), password: null, X509KeyStorageFlags.Exportable);
private static string Sanitize(string name) => new(name.Where(c => char.IsLetterOrDigit(c) || c is ' ' or '-' or '.').Take(60).ToArray());
}