using FastGithub.ReverseProxy; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; namespace FastGithub { /// /// Kestrel扩展 /// public static class KestrelServerOptionsExtensions { /// /// 域名证书缓存 /// private static readonly IMemoryCache domainCertCache = new MemoryCache(Options.Create(new MemoryCacheOptions())); /// /// 监听https的反向代理 /// /// public static void ListenHttpsReverseProxy(this KestrelServerOptions kestrel) { var loggerFactory = kestrel.ApplicationServices.GetRequiredService(); var logger = loggerFactory.CreateLogger($"{nameof(FastGithub)}.{nameof(ReverseProxy)}"); const string CAPATH = "CACert"; Directory.CreateDirectory(CAPATH); var caPublicCerPath = $"{CAPATH}/{nameof(FastGithub)}.cer"; var caPrivateKeyPath = $"{CAPATH}/{nameof(FastGithub)}.key"; GeneratorCaCert(caPublicCerPath, caPrivateKeyPath); InstallCaCert(caPublicCerPath, logger); kestrel.Listen(IPAddress.Any, 443, listen => listen.UseHttps(https => https.ServerCertificateSelector = (ctx, domain) => GetDomainCert(domain, caPublicCerPath, caPrivateKeyPath))); } /// /// 生成根证书 /// 10年 /// /// /// private static void GeneratorCaCert(string caPublicCerPath, string caPrivateKeyPath) { if (File.Exists(caPublicCerPath) && File.Exists(caPublicCerPath)) { return; } File.Delete(caPublicCerPath); File.Delete(caPrivateKeyPath); var validFrom = DateTime.Today.AddDays(-1); var validTo = DateTime.Today.AddYears(10); CertGenerator.GenerateBySelf(new[] { nameof(FastGithub) }, 2048, validFrom, validTo, caPublicCerPath, caPrivateKeyPath); } /// /// 安装根证书 /// /// /// private static void InstallCaCert(string caPublicCerPath, ILogger logger) { if (OperatingSystem.IsWindows() == false) { logger.LogWarning($"不支持自动安装证书{caPublicCerPath}:请手动安装证书到根证书颁发机构"); } else { try { var caCert = new X509Certificate2(caPublicCerPath); using var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); if (store.Certificates.Find(X509FindType.FindByThumbprint, caCert.Thumbprint, true).Count == 0) { store.Add(caCert); store.Close(); } } catch (Exception) { logger.LogWarning($"安装证书{caPublicCerPath}失败:请手动安装到“将所有的证书都放入下载存储”\\“受信任的根证书颁发机构”"); } } } /// /// 获取颁发给指定域名的证书 /// /// /// /// /// private static X509Certificate2 GetDomainCert(string? domain, string caPublicCerPath, string caPrivateKeyPath) { return domainCertCache.GetOrCreate(domain ?? string.Empty, GetOrCreateCert); // 生成域名的1年证书 X509Certificate2 GetOrCreateCert(ICacheEntry entry) { var host = (string)entry.Key; var domains = GetDomains(host).Distinct(); var validFrom = DateTime.Today.AddDays(-1); var validTo = DateTime.Today.AddYears(1); entry.SetAbsoluteExpiration(validTo); return CertGenerator.GenerateByCa(domains, 2048, validFrom, validTo, caPublicCerPath, caPrivateKeyPath); } } /// /// 获取域名 /// /// /// private static IEnumerable GetDomains(string host) { if (string.IsNullOrEmpty(host) == false) { yield return host; } yield return Environment.MachineName; yield return IPAddress.Loopback.ToString(); foreach (var @interface in NetworkInterface.GetAllNetworkInterfaces()) { foreach (var addressInfo in @interface.GetIPProperties().UnicastAddresses) { if (addressInfo.Address.AddressFamily == AddressFamily.InterNetwork) { yield return addressInfo.Address.ToString(); } } } } } }