示例#1
0
        private static void ConfigureHttps(HttpsConnectionAdapterOptions options)
        {
            try
            {
                // When we get the certificate from Key Vault as a secret,
                // it provides the entire PFX file but without the password.
                // Since PFX is a binary format and a secret is a string,
                // it is base64 encoded. So we read in the text file and convert
                // it to the bytes to initialize the X509Certificate2.
                var certPath = Environment.GetEnvironmentVariable("HTTPS_CERTIFICATE_PATH");
                if (!string.IsNullOrEmpty(certPath))
                {
                    var certString = System.IO.File.ReadAllText(certPath);
                    var certBytes  = Convert.FromBase64String(certString);
                    var httpsCert  = new X509Certificate2(certBytes);

                    Console.WriteLine($"HTTPS cert Subject:    {httpsCert.Subject}");
                    Console.WriteLine($"HTTPS cert Thumbprint: {httpsCert.Thumbprint}");

                    // set the Kestrel HTTPS certificate
                    options.ServerCertificate = httpsCert;
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine($"unable to load https cert: {ex}");
                throw;
            }
        }
示例#2
0
        /// <summary>
        /// Apply the SSL Certificate and Port details to the <see cref="IWebHostBuilder"/>.
        /// </summary>
        private static void UseKestrel(this IWebHostBuilder webHostBuilder, HostConfig serviceConfig, bool validOnly)
        {
            if (webHostBuilder == null)
            {
                throw new ArgumentNullException(nameof(webHostBuilder));
            }
            if (serviceConfig == null)
            {
                throw new ArgumentNullException(nameof(serviceConfig));
            }

            var sslCertificate = LoadCertificate(serviceConfig.SslCertThumbprint, validOnly);

            webHostBuilder.UseKestrel(options =>
            {
                options.Listen(new IPEndPoint(IPAddress.Loopback, serviceConfig.Port), listenOptions =>
                {
                    var httpsConnectionAdapterOptions = new HttpsConnectionAdapterOptions
                    {
                        ClientCertificateMode       = ClientCertificateMode.AllowCertificate,
                        SslProtocols                = SslProtocols.Tls12, // Tls 1.0 and 1.1 are broken
                        ServerCertificate           = sslCertificate,
                        ClientCertificateValidation = (certificate2, chain, sslPolicyErrors) => true
                    };
                    listenOptions.NoDelay = true;
                    listenOptions.UseHttps(httpsConnectionAdapterOptions).UseConnectionLogging();
                });
            });

            webHostBuilder.UseUrls($"https://*:{serviceConfig.Port}");
        }
示例#3
0
 /// <summary>
 /// Configure HTTPS certificates dynamically with an implementation of <see cref="IServerCertificateSelector"/>.
 /// </summary>
 /// <param name="httpsOptions">The HTTPS configuration</param>
 /// <param name="certificateSelector">The server certificate selector.</param>
 /// <returns>The HTTPS configuration</returns>
 public static HttpsConnectionAdapterOptions UseServerCertificateSelector(
     this HttpsConnectionAdapterOptions httpsOptions,
     IServerCertificateSelector certificateSelector)
 {
     httpsOptions.ServerCertificateSelector = certificateSelector.Select;
     return(httpsOptions);
 }
示例#4
0
        public IWebHostBuilder CreateKestrelBuilder()
        {
            Validate();
            var webHostBuilder = new WebHostBuilder()
                                 .UseKestrel(kestrel => {
                kestrel.Limits.MaxRequestBodySize = null;

                var adapterOptions = new HttpsConnectionAdapterOptions {
                    ClientCertificateMode       = ClientCertificateMode.AllowCertificate,
                    ClientCertificateValidation = Authentication.ValidateClientPeerCertificate,
                    ServerCertificateSelector   = (c, n) => Authentication.GetCurrentCertificate(),
                    CheckCertificateRevocation  = false,
                };

                foreach (var ip in new EndpointNameResolver().ResolveToIPEndPoints(ServerUrl))
                {
                    kestrel.Listen(ip, x => x.UseHttps(adapterOptions));
                }
            })
                                 .ConfigureServices(services => {
                services.AddSingleton(typeof(ICaberMutualAuthentication), Authentication);
                services.AddSingleton(RequestRouter);
                services.AddSingleton <ICaberRequestHandler, CaberRequestHandler>();
                services.AddTransient <CaberRequestErrorLogger>();

                services.AddAuthentication(x => x.DefaultScheme = CaberMutualAuthenticationHandler.SchemeName)
                .AddScheme <AuthenticationSchemeOptions, CaberMutualAuthenticationHandler>(CaberMutualAuthenticationHandler.SchemeName, CaberMutualAuthenticationHandler.SchemeDescription, o => { });
            })
                                 .UseStartup <Startup>();

            return(webHostBuilder);
        }
示例#5
0
 // Additional configuration is required to successfully run gRPC on macOS.
 // For instructions on how to configure Kestrel and gRPC clients on macOS, visit https://go.microsoft.com/fwlink/?linkid=2099682
 public static IHostBuilder CreateHostBuilder(string[] args) =>
 Host.CreateDefaultBuilder(args)
 .ConfigureWebHostDefaults(webBuilder =>
 {
     webBuilder.UseStartup <Startup>();
     webBuilder.ConfigureKestrel(kerstrel =>
     {
         kerstrel.Listen(IPAddress.Any, 5000, o => o.Protocols = HttpProtocols.Http1AndHttp2);
         kerstrel.Listen(IPAddress.Any, 5001, listenOptions =>
         {
             var serverPath                    = AppDomain.CurrentDomain.BaseDirectory + "cert\\server.pfx";
             var serverCertificate             = new X509Certificate2(serverPath, "123456789");
             var httpsConnectionAdapterOptions = new HttpsConnectionAdapterOptions()
             {
                 ClientCertificateMode = ClientCertificateMode.AllowCertificate,
                 SslProtocols          = System.Security.Authentication.SslProtocols.Tls12,
                 //用chain.Build验证客户端证书
                 ClientCertificateValidation = (cer, chain, error) =>
                 {
                     return(chain.Build(cer));
                 },
                 ServerCertificate = serverCertificate
             };
             listenOptions.UseHttps(httpsConnectionAdapterOptions);
             listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
         });
     });
 });
        /// <summary>
        /// Configure Kestrel to use HTTPS.
        /// </summary>
        /// <param name="listenOptions">
        /// The <see cref="ListenOptions"/> to configure.
        /// </param>
        /// <param name="httpsOptions">
        /// Options to configure HTTPS.
        /// </param>
        /// <returns>
        /// The <see cref="ListenOptions"/>.
        /// </returns>
        public static ListenOptions UseHttps(this ListenOptions listenOptions, HttpsConnectionAdapterOptions httpsOptions)
        {
            var loggerFactory = listenOptions.KestrelServerOptions.ApplicationServices.GetRequiredService <ILoggerFactory>();

            listenOptions.ConnectionAdapters.Add(new HttpsConnectionAdapter(httpsOptions, loggerFactory));
            return(listenOptions);
        }
示例#7
0
        // Additional configuration is required to successfully run gRPC on macOS.
        // For instructions on how to configure Kestrel and gRPC clients on macOS, visit https://go.microsoft.com/fwlink/?linkid=2099682
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .UseSystemd()
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup <Startup>()
            .ConfigureKestrel(options =>
            {
                options.Limits.MinRequestBodyDataRate = null;
                options.Listen(IPAddress.Any, PORT,
                               listenOptions =>
                {
                    var httpsConnectionAdapterOptions = new HttpsConnectionAdapterOptions()
                    {
                        ClientCertificateMode = ClientCertificateMode.AllowCertificate,
                        SslProtocols          = System.Security.Authentication.SslProtocols.Tls,
                    };

                    listenOptions.UseHttps("grpcServer.pfx", "1511");

                    listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
                });
            });
        })
        .ConfigureServices(services =>
        {
            services.AddHostedService <NodeService>();
        });
        /// <summary>
        /// Starts listening at the specified port.
        /// </summary>
        public void Start()
        {
            Startup.Listener = this;
            m_host           = new WebHostBuilder();
#if NETSTANDARD2_0
            HttpsConnectionAdapterOptions httpsOptions = new HttpsConnectionAdapterOptions();
            httpsOptions.CheckCertificateRevocation = false;
            httpsOptions.ClientCertificateMode      = ClientCertificateMode.NoCertificate;
            httpsOptions.ServerCertificate          = m_serverCert;
            httpsOptions.SslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12;
            m_host.UseKestrel(options =>
            {
                options.Listen(IPAddress.Any, m_uri.Port, listenOptions =>
                {
                    listenOptions.NoDelay = true;
                    listenOptions.UseHttps(httpsOptions);
                });
            });
#else
            HttpsConnectionFilterOptions httpsOptions = new HttpsConnectionFilterOptions();
            httpsOptions.CheckCertificateRevocation = false;
            httpsOptions.ClientCertificateMode      = ClientCertificateMode.NoCertificate;
            httpsOptions.ServerCertificate          = m_serverCert;
            httpsOptions.SslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12;
            m_host.UseKestrel(options =>
            {
                options.NoDelay = true;
                options.UseHttps(httpsOptions);
            });
#endif
            m_host.UseContentRoot(Directory.GetCurrentDirectory());
            m_host.UseStartup <Startup>();
            m_host.Start(Utils.ReplaceLocalhost(m_uri.ToString()));
        }
        /// <summary>
        /// Starts listening at the specified port.
        /// </summary>
        public void Start()
        {
            Startup.Listener = this;
            m_hostBuilder    = new WebHostBuilder();
            HttpsConnectionAdapterOptions httpsOptions = new HttpsConnectionAdapterOptions();

            httpsOptions.CheckCertificateRevocation = false;
            httpsOptions.ClientCertificateMode      = ClientCertificateMode.NoCertificate;
            httpsOptions.ServerCertificate          = m_serverCert;

            // note: although security tools recommend 'None' here,
            // it only works on .NET 4.6.2 if Tls12 is used
#if NET462
            httpsOptions.SslProtocols = SslProtocols.Tls12;
#else
            httpsOptions.SslProtocols = SslProtocols.None;
#endif
            m_hostBuilder.UseKestrel(options => {
                options.ListenAnyIP(m_uri.Port, listenOptions => {
                    listenOptions.UseHttps(httpsOptions);
                });
            });

            m_hostBuilder.UseContentRoot(Directory.GetCurrentDirectory());
            m_hostBuilder.UseStartup <Startup>();
            m_host = m_hostBuilder.Start(Utils.ReplaceLocalhost(m_uri.ToString()));
        }
        /// <summary>
        /// Configured LettuceEncrypt on this HTTPS endpoint for Kestrel.
        /// </summary>
        /// <param name="httpsOptions">Kestrel's HTTPS configuration</param>
        /// <param name="applicationServices"></param>
        /// <returns>The original HTTPS options with some required settings added to it.</returns>
        /// <exception cref="InvalidOperationException">
        /// Raised if <see cref="LettuceEncryptServiceCollectionExtensions.AddLettuceEncrypt(Microsoft.Extensions.DependencyInjection.IServiceCollection)"/>
        /// has not been used to add required services to the application service provider
        /// </exception>
        public static HttpsConnectionAdapterOptions UseLettuceEncrypt(
            this HttpsConnectionAdapterOptions httpsOptions,
            IServiceProvider applicationServices)
        {
            var selector = applicationServices.GetService <IServerCertificateSelector>();

            if (selector is null)
            {
                throw new InvalidOperationException(MissingServicesMessage);
            }

#if NETCOREAPP3_0
            var tlsResponder = applicationServices.GetService <TlsAlpnChallengeResponder>();
            if (tlsResponder is null)
            {
                throw new InvalidOperationException(MissingServicesMessage);
            }

            return(httpsOptions.UseLettuceEncrypt(selector, tlsResponder));
#elif NETSTANDARD2_0
            return(httpsOptions.UseServerCertificateSelector(selector));
#else
#error Update TFMs
#endif
        }
        public HttpsConnectionAdapter(HttpsConnectionAdapterOptions options, ILoggerFactory loggerFactory)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            // This configuration will always fail per-request, preemptively fail it here. See HttpConnection.SelectProtocol().
            if (options.HttpProtocols == HttpProtocols.Http2 && RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                throw new NotSupportedException(CoreStrings.HTTP2NoTlsOsx);
            }

            // capture the certificate now so it can't be switched after validation
            _serverCertificate         = options.ServerCertificate;
            _serverCertificateSelector = options.ServerCertificateSelector;
            if (_serverCertificate == null && _serverCertificateSelector == null)
            {
                throw new ArgumentException(CoreStrings.ServerCertificateRequired, nameof(options));
            }

            // If a selector is provided then ignore the cert, it may be a default cert.
            if (_serverCertificateSelector != null)
            {
                // SslStream doesn't allow both.
                _serverCertificate = null;
            }
            else
            {
                EnsureCertificateIsAllowedForServerAuth(_serverCertificate);
            }

            _options = options;
            _logger  = loggerFactory?.CreateLogger <HttpsConnectionAdapter>() ?? (ILogger)NullLogger.Instance;
        }
示例#12
0
        public HttpsConnectionAdapter(HttpsConnectionAdapterOptions options, ILoggerFactory loggerFactory)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            // capture the certificate now so it can't be switched after validation
            _serverCertificate         = options.ServerCertificate;
            _serverCertificateSelector = options.ServerCertificateSelector;
            if (_serverCertificate == null && _serverCertificateSelector == null)
            {
                throw new ArgumentException(CoreStrings.ServerCertificateRequired, nameof(options));
            }

            // If a selector is provided then ignore the cert, it may be a default cert.
            if (_serverCertificateSelector != null)
            {
                // SslStream doesn't allow both.
                _serverCertificate = null;
            }
            else
            {
                EnsureCertificateIsAllowedForServerAuth(_serverCertificate);
            }

            _options = options;
            _logger  = loggerFactory?.CreateLogger(nameof(HttpsConnectionAdapter));
        }
示例#13
0
        public HttpsConnectionMiddleware(ConnectionDelegate next, HttpsConnectionAdapterOptions options, ILoggerFactory loggerFactory)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (options.ServerCertificate == null && options.ServerCertificateSelector == null)
            {
                throw new ArgumentException(CoreStrings.ServerCertificateRequired, nameof(options));
            }

            _next             = next;
            _handshakeTimeout = options.HandshakeTimeout;
            _logger           = loggerFactory.CreateLogger <HttpsConnectionMiddleware>();

            // Something similar to the following could allow us to remove more duplicate logic, but we need https://github.com/dotnet/runtime/issues/40402 to be fixed first.
            //var sniOptionsSelector = new SniOptionsSelector("", new Dictionary<string, SniConfig> { { "*", new SniConfig() } }, new NoopCertificateConfigLoader(), options, options.HttpProtocols, _logger);
            //_httpsOptionsCallback = SniOptionsSelector.OptionsCallback;
            //_httpsOptionsCallbackState = sniOptionsSelector;
            //_sslStreamFactory = s => new SslStream(s);

            _options = options;
            _options.HttpProtocols = ValidateAndNormalizeHttpProtocols(_options.HttpProtocols, _logger);

            // capture the certificate now so it can't be switched after validation
            _serverCertificate         = options.ServerCertificate;
            _serverCertificateSelector = options.ServerCertificateSelector;

            // If a selector is provided then ignore the cert, it may be a default cert.
            if (_serverCertificateSelector != null)
            {
                // SslStream doesn't allow both.
                _serverCertificate = null;
            }
            else
            {
                Debug.Assert(_serverCertificate != null);

                EnsureCertificateIsAllowedForServerAuth(_serverCertificate);

                var certificate = _serverCertificate;
                if (!certificate.HasPrivateKey)
                {
                    // SslStream historically has logic to deal with certificate missing private keys.
                    // By resolving the SslStreamCertificateContext eagerly, we circumvent this logic so
                    // try to resolve the certificate from the store if there's no private key in the cert.
                    certificate = LocateCertificateWithPrivateKey(certificate);
                }

                // This might be do blocking IO but it'll resolve the certificate chain up front before any connections are
                // made to the server
                _serverCertificateContext = SslStreamCertificateContext.Create(certificate, additionalCertificates: null);
            }

            var remoteCertificateValidationCallback = _options.ClientCertificateMode == ClientCertificateMode.NoCertificate ?
                                                      (RemoteCertificateValidationCallback?)null : RemoteCertificateValidationCallback;

            _sslStreamFactory = s => new SslStream(s, leaveInnerStreamOpen: false, userCertificateValidationCallback: remoteCertificateValidationCallback);
        }
示例#14
0
        public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .UseStartup <Startup>()
        .UseKestrel(options =>
        {
            options.Listen(new IPEndPoint(IPAddress.Any, 44347), listenOptions =>
            {
                HttpsConnectionAdapterOptions adapterOptions = new HttpsConnectionAdapterOptions()
                {
                    ClientCertificateMode = ClientCertificateMode.AllowCertificate,
                    SslProtocols          = SslProtocols.Tls,
                    ServerCertificate     = Startup.GetMachineCertificate(),
                };

                listenOptions.UseHttps(adapterOptions);
            });

            options.Listen(new IPEndPoint(IPAddress.Any, 44348), listenOptions =>
            {
                HttpsConnectionAdapterOptions adapterOptions = new HttpsConnectionAdapterOptions()
                {
                    ClientCertificateMode = ClientCertificateMode.NoCertificate,
                    SslProtocols          = SslProtocols.Tls,
                    ServerCertificate     = Startup.GetMachineCertificate(),
                };

                listenOptions.UseHttps(adapterOptions);
            });
        })
        .UseIISIntegration()
        .UseStartup <Startup>()
        .Build();
示例#15
0
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseStartup <Startup>()
                       .UseKestrel(options =>
            {
                options.Limits.MaxRequestBodySize = 1 * 1024 * 1024 * 1024;     // 1GB
                var configuration = Startup._kestrelConfiguration;
                if (configuration != null)
                {
                    options.Listen(IPAddress.Any, configuration.HttpsListenPort, listenOptions =>
                    {
                        var httpsOptions = new HttpsConnectionAdapterOptions();
                        httpsOptions.ServerCertificate = new X509Certificate2(
                            configuration.ServerCertificatePath, configuration.ServerCertificatePassword);
                        httpsOptions.ClientCertificateMode       = ClientCertificateMode.RequireCertificate;
                        httpsOptions.ClientCertificateValidation = (cert, chain, errors) =>
                        {
                            // 检查客户端证书
                            // return cert.Equals(clientCertificate);
                            return(chain.Build(cert));
                        };
                        httpsOptions.SslProtocols = SslProtocols.Tls;
                        listenOptions.UseHttps(httpsOptions);
                    });
                }
            })
                       .UseIISIntegration()
                       .Build();

            host.Run();
        }
        private async Task StartServiceRequiringClientCertificate()
        {
            try
            {
                _serviceHostRequiringClientCertificate = WebHost.CreateDefaultBuilder()
                                                         .UseKestrel(o =>
                {
                    var adapterOptions = new HttpsConnectionAdapterOptions
                    {
                        ClientCertificateMode       = ClientCertificateMode.RequireCertificate,
                        SslProtocols                = SslProtocols.Tls12,
                        ServerCertificate           = new X509Certificate2(Convert.FromBase64String(ServerCertificate), ServerCertificatePassword),
                        ClientCertificateValidation = (cert, chain, p) =>
                                                      string.Equals(cert.Thumbprint, ClientCertificateThumbprint, StringComparison.OrdinalIgnoreCase)
                    };

                    o.Listen(IPAddress.Any, ServiceRequiringClientCertificatePort, l => l.UseHttps(adapterOptions));
                })
                                                         .UseStartup <Startup>()
                                                         .Build();

                await _serviceHostRequiringClientCertificate.StartAsync();
            }
            catch (Exception e)
            {
                TestContext.WriteLine(e);
            }
        }
示例#17
0
 public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
 WebHost.CreateDefaultBuilder(args)
 .UseKestrel(options =>
 {
     options.Listen(IPAddress.Any, 80);
     options.Listen(IPAddress.Any, 443, listenOptions =>
     {
         var signingCertificate            = new X509Certificate2("server.pfx", "111111");
         var httpsConnectionAdapterOptions = new HttpsConnectionAdapterOptions()
         {
             ClientCertificateMode = ClientCertificateMode.RequireCertificate,        //AllowCertificate,
             SslProtocols          = System.Security.Authentication.SslProtocols.Tls12,
             //验证客户器证书是否正规
             ClientCertificateValidation = (cer, chain, error) =>
             {
                 var res = chain.Build(cer);
                 Console.WriteLine($"*********  验证客户端证书 chain.Build={res}");
                 return(res);
             },
             ServerCertificate = signingCertificate
         };
         listenOptions.UseHttps(httpsConnectionAdapterOptions);
     });
 })
 .UseStartup <Startup>();
示例#18
0
        public static void Configure(IWebHostBuilder webBuilder, IConfiguration configuration)
        {
            var httpProtocol = configuration["devonfw:Kestrel:HttpProtocol"];
            var sslProtocol  = configuration["devonfw:Kestrel:SslProtocol"];

            _ = int.TryParse(configuration["devonfw:Kestrel:ApplicationPort"], out int applicationPort);
            _ = bool.TryParse(configuration["devonfw:Kestrel:UseHttps"], out bool useHttps);


            webBuilder.UseKestrel(options =>
            {
                options.AddServerHeader = false;
                options.Listen(IPAddress.Any, applicationPort, listenOptions =>
                {
                    listenOptions.Protocols = ProtocolOperations.GetHttProtocol(httpProtocol);
                    SetupCommonProperties(configuration, options);

                    if (!useHttps)
                    {
                        return;
                    }

                    var httpsOptions = new HttpsConnectionAdapterOptions();
                    SetupHttpsProperties(configuration, sslProtocol, httpsOptions);
                    listenOptions.UseHttps(httpsOptions);
                });
            });
        }
示例#19
0
        public static IWebHost BuildWebHost() =>
        WebHost.CreateDefaultBuilder()
        .UseKestrel(
            options =>
        {
#if DEBUG
            options.Listen(IPAddress.Loopback, 5000);
            backendServerPort = 5000;
#else
            // Get free TCP port and write it to STDOUT where the Electron frontend can catch it.
            backendServerPort = FindFreeTcpPort();
            options.Listen(IPAddress.Loopback, backendServerPort, listenOptions =>
            {
                var httpsOptions =
                    new HttpsConnectionAdapterOptions
                {
                    ServerCertificate =
                        CertificateGenerator
                        .GenerateCertificate(
                            $"CN={DigestUtils.GetDigestFromAssembly(typeof(Program).Assembly).ToLowerInvariant()}")
                };

                listenOptions.UseHttps(httpsOptions);
            });
#endif
        })
        .UseStartup <Startup>()
        .Build();
    public void FallsBackToHttpsConnectionAdapterServerCertificateSelectorOverServerCertificate()
    {
        var sniDictionary = new Dictionary <string, SniConfig>
        {
            { "www.example.org", new SniConfig() }
        };

        var selectorCertificate = _x509Certificate2;

        var fallbackOptions = new HttpsConnectionAdapterOptions
        {
            ServerCertificate         = new X509Certificate2(Array.Empty <byte>()),
            ServerCertificateSelector = (context, serverName) => selectorCertificate
        };

        var sniOptionsSelector = new SniOptionsSelector(
            "TestEndpointName",
            sniDictionary,
            new MockCertificateConfigLoader(),
            fallbackOptions,
            fallbackHttpProtocols: HttpProtocols.Http1AndHttp2,
            logger: Mock.Of <ILogger <HttpsConnectionMiddleware> >());

        var(options, _) = sniOptionsSelector.GetOptions(new MockConnectionContext(), "www.example.org");
        Assert.Same(selectorCertificate, options.ServerCertificate);
    }
示例#21
0
 internal EndpointConfiguration(bool isHttps, ListenOptions listenOptions, HttpsConnectionAdapterOptions httpsOptions, IConfigurationSection configSection)
 {
     IsHttps       = isHttps;
     ListenOptions = listenOptions ?? throw new ArgumentNullException(nameof(listenOptions));
     HttpsOptions  = httpsOptions ?? throw new ArgumentNullException(nameof(httpsOptions));
     ConfigSection = configSection ?? throw new ArgumentNullException(nameof(configSection));
 }
示例#22
0
        public static void Main(string[] args)
        {
            var whb = WebHost.CreateDefaultBuilder(args);

            var environment = whb.GetSetting("environment");
            var subjectName = GetCertificateSubjectNameBasedOnEnvironment(environment);
            var certificate = GetServiceCertificate(subjectName);

            var host = whb.UseStartup <Startup>()
                       .UseKestrel(options =>
            {
                options.Listen(new IPEndPoint(IPAddress.Loopback, 4430), listenOptions =>
                {
                    var httpsConnectionAdapterOptions = new HttpsConnectionAdapterOptions()
                    {
                        ClientCertificateMode = ClientCertificateMode.AllowCertificate,
                        SslProtocols          = System.Security.Authentication.SslProtocols.Tls,
                        ServerCertificate     = certificate
                    };
                    listenOptions.UseHttps(httpsConnectionAdapterOptions);
                });
            })
                       .Build();

            host.Run();
        }
示例#23
0
        private static X509Certificate2 GetCertificateFromOptions(ListenOptions listenOption)
        {
            X509Certificate2 cert = null;

            FieldInfo middlewareProp = typeof(ListenOptions).GetField("_middleware", BindingFlags.Instance | BindingFlags.NonPublic);
            List <Func <ConnectionDelegate, ConnectionDelegate> > middleware = (List <Func <ConnectionDelegate, ConnectionDelegate> >)middlewareProp.GetValue(listenOption);

            if (middleware == null)
            {
                return(cert);
            }

            foreach (var mid in middleware)
            {
                var       target           = mid.Target; // a generated type
                FieldInfo httpsOptionsProp = target.GetType().GetField("httpsOptions", BindingFlags.Instance | BindingFlags.Public);
                if (httpsOptionsProp == null)
                {
                    continue;
                }
                HttpsConnectionAdapterOptions httpsOptions = httpsOptionsProp.GetValue(target) as HttpsConnectionAdapterOptions;
                if (httpsOptions == null)
                {
                    continue;
                }
                cert = httpsOptions.ServerCertificate;
            }
            return(cert);
        }
        public void Load()
        {
            if (Options.ConfigurationLoader == null)
            {
                // The loader has already been run.
                return;
            }
            Options.ConfigurationLoader = null;

            var configReader = new ConfigurationReader(Configuration);

            LoadDefaultCert(configReader);

            foreach (var endpoint in configReader.Endpoints)
            {
                var listenOptions = AddressBinder.ParseAddress(endpoint.Url, out var https);
                Options.ApplyEndpointDefaults(listenOptions);

                // Compare to UseHttps(httpsOptions => { })
                var httpsOptions = new HttpsConnectionAdapterOptions();
                if (https)
                {
                    // Defaults
                    Options.ApplyHttpsDefaults(httpsOptions);

                    // Specified
                    httpsOptions.ServerCertificate = LoadCertificate(endpoint.Certificate, endpoint.Name)
                                                     ?? httpsOptions.ServerCertificate;

                    // Fallback
                    Options.ApplyDefaultCert(httpsOptions);
                }

                if (EndpointConfigurations.TryGetValue(endpoint.Name, out var configureEndpoint))
                {
                    var endpointConfig = new EndpointConfiguration(https, listenOptions, httpsOptions, endpoint.ConfigSection);
                    configureEndpoint(endpointConfig);
                }

                // EndpointDefaults or configureEndpoint may have added an https adapter.
                if (https && !listenOptions.ConnectionAdapters.Any(f => f.IsHttps))
                {
                    if (httpsOptions.ServerCertificate == null && httpsOptions.ServerCertificateSelector == null)
                    {
                        throw new InvalidOperationException(CoreStrings.NoCertSpecifiedNoDevelopmentCertificateFound);
                    }

                    listenOptions.UseHttps(httpsOptions);
                }

                Options.ListenOptions.Add(listenOptions);
            }

            foreach (var action in EndpointsToAdd)
            {
                action();
            }
        }
        public void HttpsExtensionConnectionAdapterTestInvalidOptions_Fails()
        {
            var options = new HttpsConnectionAdapterOptions()
            {
                ServerCertificate = null
            };

            Assert.Throws <ArgumentNullException>(() => new HttpsExtensionConnectionAdapter(options));
        }
        public void HttpsExtensionConnectionAdapterTestValidCertWithEkuClient_Fails()
        {
            var(cert, key) = TestCertificateHelper.GenerateClientert("eku client auth", DateTime.Now.Subtract(TimeSpan.FromDays(2)), DateTime.Now.AddYears(1));
            var options = new HttpsConnectionAdapterOptions()
            {
                ServerCertificate = cert
            };

            Assert.Throws <InvalidOperationException>(() => new HttpsExtensionConnectionAdapter(options));
        }
        public void HttpsExtensionConnectionAdapterTestValidCertWithEkuServer_Succeeds()
        {
            var(cert, key) = TestCertificateHelper.GenerateServerCert("eku server auth", DateTime.Now.Subtract(TimeSpan.FromDays(2)), DateTime.Now.AddYears(1));
            var options = new HttpsConnectionAdapterOptions()
            {
                ServerCertificate = cert
            };

            Assert.NotNull(new HttpsExtensionConnectionAdapter(options));
        }
        public void HttpsExtensionConnectionAdapterTestValidCertWithNoEku_Succeeds()
        {
            var cert    = TestCertificateHelper.GenerateSelfSignedCert("no eku");
            var options = new HttpsConnectionAdapterOptions()
            {
                ServerCertificate = cert
            };

            Assert.NotNull(new HttpsExtensionConnectionAdapter(options));
        }
        public static ListenOptions UseLetsEncrypt(this ListenOptions options)
        {
            _ = LoadCertificate("peoplemeter.ru", "*****@*****.**");

            var httpsOptions = new HttpsConnectionAdapterOptions {
                ServerCertificateSelector = ServerCertificateSelector
            };

            return(options.UseHttps(httpsOptions));
        }
示例#30
0
        public void Http2ThrowsOnIncompatibleWindowsVersions()
        {
            var httpConnectionAdapterOptions = new HttpsConnectionAdapterOptions
            {
                ServerCertificate = _x509Certificate2,
                HttpProtocols     = HttpProtocols.Http2
            };

            Assert.Throws <NotSupportedException>(() => new HttpsConnectionMiddleware(context => Task.CompletedTask, httpConnectionAdapterOptions));
        }