private HttpMessageHandler CreateHttpMessageHandler(IWebHostEnvironment env)
        {
            var httpClientHandler = new HttpClientHandler();

            if (_spineConfig.UseSSP)
            {
                httpClientHandler.SslProtocols = SslProtocols.Tls13 | SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls;

                var clientCertData        = CertificateHelper.ExtractCertInstances(_spineConfig.ClientCert);
                var clientPrivateKeyData  = CertificateHelper.ExtractKeyInstance(_spineConfig.ClientPrivateKey);
                var x509ClientCertificate = new X509Certificate2(clientCertData.FirstOrDefault());
                var privateKey            = RSA.Create();
                privateKey.ImportRSAPrivateKey(clientPrivateKeyData, out _);
                var x509CertificateWithPrivateKey = x509ClientCertificate.CopyWithPrivateKey(privateKey);
                var pfxFormattedCertificate       = new X509Certificate2(x509CertificateWithPrivateKey.Export(X509ContentType.Pfx, string.Empty), string.Empty);

                var serverCertData              = CertificateHelper.ExtractCertInstances(_spineConfig.ServerCACertChain);
                var x509ServerCertificateSubCa  = new X509Certificate2(serverCertData[0]);
                var x509ServerCertificateRootCa = new X509Certificate2(serverCertData[1]);

                httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => ValidateServerCertificateChain(chain, x509ServerCertificateSubCa, x509ServerCertificateRootCa, pfxFormattedCertificate);

                httpClientHandler.ClientCertificates.Add(pfxFormattedCertificate);
                httpClientHandler.ClientCertificateOptions = ClientCertificateOption.Manual;
                return(httpClientHandler);
            }
            return(httpClientHandler);
        }
Ejemplo n.º 2
0
        private static HttpMessageHandler CreateHttpMessageHandler(IConfiguration configuration, IWebHostEnvironment env)
        {
            var clientCert       = configuration.GetSection("spine:client_cert").GetConfigurationString();
            var serverCert       = configuration.GetSection("spine:server_ca_certchain").GetConfigurationString();
            var clientPrivateKey = configuration.GetSection("spine:client_private_key").GetConfigurationString();

            var httpClientHandler = new HttpClientHandler();

            if (bool.Parse(configuration.GetSection("spine:use_ssp").GetConfigurationString("false")) &&
                !string.IsNullOrEmpty(clientCert) && !string.IsNullOrEmpty(clientPrivateKey) &&
                !string.IsNullOrEmpty(configuration.GetSection("spine:nhsMHSEndPoint").GetConfigurationString()))
            {
                httpClientHandler.SslProtocols = SslProtocols.Tls13 | SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls;

                var clientCertData        = CertificateHelper.ExtractCertInstances(clientCert);
                var clientPrivateKeyData  = CertificateHelper.ExtractKeyInstance(clientPrivateKey);
                var x509ClientCertificate = new X509Certificate2(clientCertData.FirstOrDefault());
                var privateKey            = RSA.Create();
                privateKey.ImportRSAPrivateKey(clientPrivateKeyData, out _);
                var x509CertificateWithPrivateKey = x509ClientCertificate.CopyWithPrivateKey(privateKey);
                var pfxFormattedCertificate       = new X509Certificate2(x509CertificateWithPrivateKey.Export(X509ContentType.Pfx, string.Empty), string.Empty);

                var serverCertData              = CertificateHelper.ExtractCertInstances(serverCert);
                var x509ServerCertificateSubCa  = new X509Certificate2(serverCertData[0]);
                var x509ServerCertificateRootCa = new X509Certificate2(serverCertData[1]);

                httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => ValidateServerCertificateChain(chain, x509ServerCertificateSubCa, x509ServerCertificateRootCa, pfxFormattedCertificate);

                httpClientHandler.ClientCertificates.Add(pfxFormattedCertificate);
                httpClientHandler.ClientCertificateOptions = ClientCertificateOption.Manual;
                return(httpClientHandler);
            }
            return(httpClientHandler);
        }
        private static void RunLdapQueries(int numberOfGoes)
        {
            string[] odsCodes = { "A20047", "X26", "J82132", "B82619", "B82617", "B82614", "J82132", "RR8" };
            var      query    = _ldapQueries.FirstOrDefault(x => x.query_name == "GetOrganisationDetailsByOdsCode");

            for (var i = 0; i < numberOfGoes; i++)
            {
                for (var j = 0; j < odsCodes.Length; j++)
                {
                    var filter  = query.query_text.Replace("{odsCode}", odsCodes[j]);
                    var results = new Dictionary <string, object>();

                    using (LdapConnection ldapConnection = new LdapConnection())
                    {
                        ldapConnection.SecureSocketLayer = _spineConfiguration.sds_use_ldaps;
                        ldapConnection.ConnectionTimeout = _spineConfiguration.timeout_seconds * 1000;

                        if (_spineConfiguration.sds_use_mutualauth)
                        {
                            System.Console.WriteLine("Using Mutual Auth");

                            var clientCertData        = CertificateHelper.ExtractCertInstances(_spineConfiguration.client_cert);
                            var clientPrivateKeyData  = CertificateHelper.ExtractKeyInstance(_spineConfiguration.client_private_key);
                            var x509ClientCertificate = new X509Certificate2(clientCertData.FirstOrDefault());

                            var privateKey = RSA.Create();
                            privateKey.ImportRSAPrivateKey(clientPrivateKeyData, out _);
                            var x509CertificateWithPrivateKey = x509ClientCertificate.CopyWithPrivateKey(privateKey);
                            var pfxFormattedCertificate       = new X509Certificate2(x509CertificateWithPrivateKey.Export(X509ContentType.Pfx, string.Empty), string.Empty);

                            _clientCertificate = pfxFormattedCertificate;

                            ldapConnection.UserDefinedServerCertValidationDelegate += ValidateServerCertificateChain;
                            ldapConnection.UserDefinedClientCertSelectionDelegate  += SelectLocalCertificate;
                        }

                        ldapConnection.Connect(_spineConfiguration.sds_hostname, _spineConfiguration.sds_port);
                        var searchResults = ldapConnection.Search(query.search_base, LdapConnection.ScopeSub, filter, null, false);

                        while (searchResults.HasMore())
                        {
                            var nextEntry    = searchResults.Next();
                            var attributeSet = nextEntry.GetAttributeSet();

                            foreach (var attribute in attributeSet)
                            {
                                results.TryAdd(attribute.Name, attribute.StringValue);
                            }
                        }
                    }
                    System.Console.WriteLine($"For query {filter} - iteration {i + 1}, result count is {results.Count}");
                }
            }
        }
Ejemplo n.º 4
0
        protected void SetupMutualAuth()
        {
            if (_spineOptionsDelegate.CurrentValue.SdsUseMutualAuth)
            {
                var clientCertData        = CertificateHelper.ExtractCertInstances(_spineOptionsDelegate.CurrentValue.ClientCert);
                var clientPrivateKeyData  = CertificateHelper.ExtractKeyInstance(_spineOptionsDelegate.CurrentValue.ClientPrivateKey);
                var x509ClientCertificate = new X509Certificate2(clientCertData.FirstOrDefault());

                var privateKey = RSA.Create();
                privateKey.ImportRSAPrivateKey(clientPrivateKeyData, out _);
                var x509CertificateWithPrivateKey = x509ClientCertificate.CopyWithPrivateKey(privateKey);
                var pfxFormattedCertificate       = new X509Certificate(x509CertificateWithPrivateKey.Export(X509ContentType.Pfx, string.Empty), string.Empty);

                _clientCertificate = pfxFormattedCertificate;
            }
        }
        private static T RunLdapQuery <T>(string odsCode, string queryName, string partyKey = "") where T : class
        {
            var query  = _ldapQueries.FirstOrDefault(x => x.query_name == queryName);
            T   result = null;

            using (var ldapConnection = new LdapConnection
            {
                SecureSocketLayer = _spineConfiguration.SdsUseLdaps,
                ConnectionTimeout = _spineConfiguration.TimeoutMilliseconds
            })
            {
                if (_spineConfiguration.SdsUseMutualAuth)
                {
                    System.Console.WriteLine("Using Mutual Auth");

                    var clientCertData        = CertificateHelper.ExtractCertInstances(_spineConfiguration.ClientCert);
                    var clientPrivateKeyData  = CertificateHelper.ExtractKeyInstance(_spineConfiguration.ClientPrivateKey);
                    var x509ClientCertificate = new X509Certificate2(clientCertData.FirstOrDefault());

                    var privateKey = RSA.Create();
                    privateKey.ImportRSAPrivateKey(clientPrivateKeyData, out _);
                    var x509CertificateWithPrivateKey = x509ClientCertificate.CopyWithPrivateKey(privateKey);
                    var pfxFormattedCertificate       = new X509Certificate2(x509CertificateWithPrivateKey.Export(X509ContentType.Pfx, string.Empty), string.Empty);

                    _clientCertificate = pfxFormattedCertificate;

                    //ldapConnection.UserDefinedServerCertValidationDelegate += ValidateServerCertificateChain;
                    //ldapConnection.UserDefinedClientCertSelectionDelegate += SelectLocalCertificate;
                }

                ldapConnection.Connect(_spineConfiguration.SdsHostname, _spineConfiguration.SdsPort);
                ldapConnection.Bind(string.Empty, string.Empty);

                var searchResults = RunSearch(ldapConnection, query, odsCode, partyKey);

                var jsonDictionary = JsonConvert.SerializeObject(searchResults);
                if (searchResults.Count > 0)
                {
                    result = JsonConvert.DeserializeObject <T>(jsonDictionary);
                }

                ldapConnection.Disconnect();
                ldapConnection.Dispose();
            }
            return(result);
        }
Ejemplo n.º 6
0
        public T ExecuteLdapQuery <T>(string searchBase, string filter, string[] attributes) where T : class
        {
            try
            {
                var sw     = new Stopwatch();
                T   result = null;
                sw.Start();
                var logMessage = new SpineMessage
                {
                    RequestPayload     = $"{searchBase} {filter} [{string.Join(",", attributes)}]",
                    SpineMessageTypeId = (int)GPConnect.Constants.SpineMessageTypes.SpineLdapQuery
                };

                var results          = new Dictionary <string, object>();
                var useLdaps         = bool.Parse(_configuration.GetSection("Spine:sds_use_ldaps").Value);
                var useSdsMutualAuth = bool.Parse(_configuration.GetSection("Spine:sds_use_mutualauth").Value);


                Novell.Directory.Ldap.LdapConnectionOptions ldapConnectionOptions = new LdapConnectionOptions();

                if (useLdaps)
                {
                    SslProtocols sslProtocol = ParseTlsVersion(_configuration.GetSection("Spine:sds_tls_version").Value);

                    ldapConnectionOptions.ConfigureSslProtocols(SslProtocols.Tls12);
                    ldapConnectionOptions.UseSsl();
                    ldapConnectionOptions.ConfigureLocalCertificateSelectionCallback(SelectLocalCertificate);
                    ldapConnectionOptions.ConfigureRemoteCertificateValidationCallback(ValidateServerCertificate);
                }

                using (var ldapConnection = new LdapConnection(ldapConnectionOptions)
                {
                    ConnectionTimeout = int.Parse(_configuration.GetSection("Spine:timeout_seconds").Value) * 1000
                })
                {
                    if (useSdsMutualAuth)
                    {
                        var clientCert       = _configuration.GetSection("spine:client_cert").GetConfigurationString();
                        var serverCert       = _configuration.GetSection("spine:server_ca_certchain").GetConfigurationString();
                        var clientPrivateKey = _configuration.GetSection("spine:client_private_key").GetConfigurationString();

                        var clientCertData        = CertificateHelper.ExtractCertInstances(clientCert);
                        var clientPrivateKeyData  = CertificateHelper.ExtractKeyInstance(clientPrivateKey);
                        var x509ClientCertificate = new X509Certificate2(clientCertData.FirstOrDefault());

                        var privateKey = RSA.Create();
                        privateKey.ImportRSAPrivateKey(clientPrivateKeyData, out _);
                        var x509CertificateWithPrivateKey = x509ClientCertificate.CopyWithPrivateKey(privateKey);
                        var pfxFormattedCertificate       = new X509Certificate(x509CertificateWithPrivateKey.Export(X509ContentType.Pfx, string.Empty), string.Empty);

                        _clientCertificate = pfxFormattedCertificate;
                    }

                    var hostName = _configuration.GetSection("Spine:sds_hostname").Value;
                    var hostPort = int.Parse(_configuration.GetSection("Spine:sds_port").Value);

                    ldapConnection.Connect(hostName, hostPort);
                    ldapConnection.Bind(string.Empty, string.Empty);

                    LogTlsVersionOnStartup(ldapConnection);

                    var searchResults = ldapConnection.Search(searchBase, LdapConnection.ScopeSub, filter, attributes, false);

                    while (searchResults.HasMore())
                    {
                        var nextEntry    = searchResults.Next();
                        var attributeSet = nextEntry.GetAttributeSet();

                        foreach (var attribute in attributeSet)
                        {
                            results.TryAdd(attribute.Name, attribute.StringValue);
                        }
                    }

                    ldapConnection.Disconnect();
                    ldapConnection.Dispose();
                }

                var jsonDictionary = JsonConvert.SerializeObject(results);
                if (results.Count > 0)
                {
                    result = JsonConvert.DeserializeObject <T>(jsonDictionary);
                }
                logMessage.ResponsePayload = jsonDictionary;
                logMessage.RoundTripTimeMs = sw.ElapsedMilliseconds;
                _logService.AddSpineMessageLog(logMessage);
                return(result);
            }
            catch (LdapException ldapException)
            {
                _logger.LogError(ldapException, "An LdapException has occurred while attempting to execute an LDAP query");
                throw;
            }
            catch (Exception exc)
            {
                _logger.LogError(exc, "An Exception has occurred while attempting to execute an LDAP query");
                throw;
            }
        }