private static void ConfigureCertificate(this KestrelServerOptions options, int port, X509Certificate2 certificate) { options.ListenLocalhost(port, listenOptions => { listenOptions.UseHttps(new HttpsConnectionAdapterOptions { ServerCertificate = certificate, ClientCertificateMode = ClientCertificateMode.RequireCertificate, ClientCertificateValidation = CertificateValidator.DisableChannelValidation, }); }); }
/// <summary> /// Configure the <see cref="KestrelServerOptions"/> with the specified URL. /// </summary> private bool Listen(KestrelServerOptions options, string url) { BindingAddress address = null; try { address = BindingAddress.Parse(url); } catch (Exception ex) { // Record the exception; it will be logged later through ILogger. Errors.Add(new AddressListenResult(url, ex)); return(false); } Action <ListenOptions> configureListenOptions = (listenOptions) => { if (address.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)) { listenOptions.UseHttps(); } }; try { if (address.Host.Equals("localhost", StringComparison.OrdinalIgnoreCase)) { options.ListenLocalhost(address.Port, configureListenOptions); } else if (IPAddress.TryParse(address.Host, out IPAddress ipAddress)) { options.Listen(ipAddress, address.Port, configureListenOptions); } else { options.ListenAnyIP(address.Port, configureListenOptions); } } catch (InvalidOperationException ex) { // This binding failure is typically due to missing default certificate. // Record the exception; it will be logged later through ILogger. Errors.Add(new AddressListenResult(url, ex)); return(false); } return(true); }
public void CanCallListenAfterConfigure() { var options = new KestrelServerOptions(); // Ensure configure doesn't throw because of missing services. var serviceCollection = new ServiceCollection(); serviceCollection.AddSingleton(Mock.Of <IHostEnvironment>()); serviceCollection.AddSingleton(Mock.Of <ILogger <KestrelServer> >()); serviceCollection.AddSingleton(Mock.Of <ILogger <HttpsConnectionMiddleware> >()); options.ApplicationServices = serviceCollection.BuildServiceProvider(); options.Configure(); // This is a regression test to verify the Listen* methods don't throw a NullReferenceException if called after Configure(). // https://github.com/dotnet/aspnetcore/issues/21423 options.ListenLocalhost(5000); }
public override void ConfigureKestrel(KestrelServerOptions options) { options.ListenLocalhost(TestsConfig.Port, listenOptions => { listenOptions.Protocols = HttpProtocols.Http2; }); }
public void ConfigureKestrelServerOptions(KestrelServerOptions opt, object?sslCertSelectorParam) { opt.AddServerHeader = !this.HideKestrelServerHeader; KestrelServerWithStackOptions?withStackOpt = opt as KestrelServerWithStackOptions; if (this.LocalHostOnly) { foreach (int port in this.HttpPortsList) { opt.ListenLocalhost(port); } foreach (int port in this.HttpsPortsList) { opt.ListenLocalhost(port, lo => EnableHttps(lo)); } } else if (this.IPv4Only) { foreach (int port in this.HttpPortsList) { opt.Listen(IPAddress.Any, port); } foreach (int port in this.HttpsPortsList) { opt.Listen(IPAddress.Any, port, lo => EnableHttps(lo)); } } else { foreach (int port in this.HttpPortsList) { opt.ListenAnyIP(port); } foreach (int port in this.HttpsPortsList) { opt.ListenAnyIP(port, lo => EnableHttps(lo)); } } opt.Limits.MaxRequestBodySize = this.MaxRequestBodySize; if (withStackOpt != null) { // Kestrel with Stack withStackOpt.TcpIp = this.TcpIp ?? LocalNet; } void EnableHttps(ListenOptions listenOptions) { listenOptions.UseHttps(httpsOptions => { httpsOptions.SslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12; bool useGlobalCertVault = false; #if CORES_BASIC_JSON #if CORES_BASIC_SECURITY useGlobalCertVault = this.UseGlobalCertVault; #endif // CORES_BASIC_JSON #endif // CORES_BASIC_SECURITY; if (useGlobalCertVault == false) { if (this.ServerCertSelector != null) { httpsOptions.ServerCertificateSelector = ((ctx, sni) => this.ServerCertSelector(sslCertSelectorParam, sni)); } } #if CORES_BASIC_JSON #if CORES_BASIC_SECURITY if (useGlobalCertVault) { if (this.GlobalCertVaultDefauleCert != null) { GlobalCertVault.SetDefaultCertificate(this.GlobalCertVaultDefauleCert); } httpsOptions.ServerCertificateSelector = ((ctx, sni) => (X509Certificate2)GlobalCertVault.GetGlobalCertVault().X509CertificateSelector(sni, !this.HasHttpPort80).NativeCertificate); } #endif // CORES_BASIC_JSON #endif // CORES_BASIC_SECURITY; }); } }
/// <summary> /// Configure Kestrel to use Certificate-based Authentication /// </summary> /// <param name="options"></param> private static void ConfigureKestrelCertAuth(KestrelServerOptions options) { using var scope = options.ApplicationServices.CreateScope(); var logger = scope.ServiceProvider .GetService <ILoggerFactory>() ?.CreateLogger(nameof(Program)); var settings = scope.ServiceProvider .GetService <IOptionsMonitor <KestrelAuthenticationConfiguration> >() ?.CurrentValue; if (settings is null) { logger.LogWarning($"{nameof(KestrelAuthenticationConfiguration)} is null, can't configure kestrel"); return; } if (!settings.Enabled) { logger.LogWarning("skipping configuration of kestrel"); return; } if (string.IsNullOrWhiteSpace(settings.Certificate)) { logger.LogError("no certificate given, provide path to a valid certificate with '" + $"{nameof(KestrelAuthenticationConfiguration)}:{nameof(KestrelAuthenticationConfiguration.Certificate)}'"); return; } X509Certificate2 certificate = null; if (Path.GetExtension(settings.Certificate) == "pfx") { certificate = settings.Password is null ? new X509Certificate2(settings.Certificate) : new X509Certificate2(settings.Certificate, settings.Password); } var certpath = Environment.GetEnvironmentVariable("ASPNETCORE_SSLCERT_PATH"); if (!string.IsNullOrEmpty(certpath) || Path.GetExtension(settings.Certificate) == "crt") { var port = Environment.GetEnvironmentVariable("ASPNETCORE_SSL_PORT"); certificate = X509CertificateUtility.LoadFromCrt(certpath) ?? X509CertificateUtility.LoadFromCrt(settings.Certificate); settings.Port = int.Parse(port ?? settings.Port.ToString()); } var connectionOptions = new HttpsConnectionAdapterOptions { ServerCertificate = certificate }; var inDocker = bool.Parse(Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER") ?? "false"); if (!inDocker) { logger.LogInformation("Not running in docker, adding client certificate validation"); connectionOptions.ClientCertificateMode = ClientCertificateMode.RequireCertificate; connectionOptions.ClientCertificateValidation = CertificateValidator.DisableChannelValidation; } logger.LogInformation($"loaded certificate: {connectionOptions.ServerCertificate}"); if (string.IsNullOrWhiteSpace(settings.IpAddress)) { logger.LogError("no ip-address given, provide a valid ipv4 or ipv6 binding-address or 'localhost' for '" + $"{nameof(KestrelAuthenticationConfiguration)}:{nameof(KestrelAuthenticationConfiguration.IpAddress)}'"); return; } if (settings.IpAddress == "localhost") { logger.LogInformation($"binding to: https://localhost:{settings.Port}"); options.ListenLocalhost(settings.Port, listenOptions => { listenOptions.UseHttps(connectionOptions); }); } else if (settings.IpAddress == "*") { logger.LogInformation($"binding to: https://*:{settings.Port}"); options.ListenAnyIP(settings.Port, listenOptions => { listenOptions.UseHttps(connectionOptions); }); } else { var ip = IPAddress.Parse(settings.IpAddress); logger.LogInformation($"binding to: https://{ip}:{settings.Port}"); options.Listen(ip, settings.Port, listenOptions => { listenOptions.UseHttps(connectionOptions); }); } }