public async Task Bind_with_client_certificate_using_obsoleted_api_is_successful() { var ldapConnectionOptions = new LdapConnectionOptions() .UseSsl() .ConfigureIpAddressFilter(ipAddress => ipAddress.AddressFamily == AddressFamily.InterNetwork) .ConfigureClientCertificates(new List <X509Certificate>() { _x509Certificate2, }); using var ldapConnection = new LdapConnection(ldapConnectionOptions); #pragma warning disable CS0618 // Type or member is obsolete ldapConnection.UserDefinedServerCertValidationDelegate += LdapConnectionUserDefinedServerCertValidationDelegate; ldapConnection.UserDefinedClientCertSelectionDelegate += LdapConnectionLocalCertificateSelectionCallback; #pragma warning restore CS0618 // Type or member is obsolete await ldapConnection.ConnectAsync(TestsConfig.LdapServer.ServerAddress, TestsConfig.LdapServer.ServerPortSsl); await ldapConnection.BindAsync(new SaslExternalRequest()); Assert.True(ldapConnection.Bound); var response = await ldapConnection.WhoAmIAsync(); Assert.Equal(_expectedAuthzId, response.AuthzId); }
public void UseSsl_enables_ssl() { var ldapConnectionOptions = new LdapConnectionOptions() .UseSsl(); Assert.True(ldapConnectionOptions.Ssl); }
public void CheckCertificateRevocation_enables_check_revocation() { var ldapConnectionOptions = new LdapConnectionOptions() .CheckCertificateRevocation(); Assert.True(ldapConnectionOptions.CheckCertificateRevocationEnabled); }
public void UseSslProtocols_enables_specific_ssl_protocols() { var ldapConnectionOptions = new LdapConnectionOptions() .ConfigureSslProtocols(SslProtocols.Tls11 | SslProtocols.Tls12); Assert.True(ldapConnectionOptions.SslProtocols.HasFlag(SslProtocols.Tls11)); Assert.True(ldapConnectionOptions.SslProtocols.HasFlag(SslProtocols.Tls12)); Assert.False(ldapConnectionOptions.SslProtocols.HasFlag(SslProtocols.Tls)); Assert.False(ldapConnectionOptions.SslProtocols.HasFlag(SslProtocols.Tls13)); }
public void UseIpAddressFilter_filters_specific_ip_address() { var ipAddressV4 = CreateRandomIpAddressV4(); bool IpAddressFilter(IPAddress ipAddress) => ipAddressV4.Equals(ipAddress); var ldapConnectionOptions = new LdapConnectionOptions() .ConfigureIpAddressFilter(IpAddressFilter); Assert.True(ldapConnectionOptions.IpAddressFilter(ipAddressV4)); }
public void UseClientCertificates_stores_certificates() { var clientCertificates = new List <X509Certificate>() { new X509Certificate(), }; var ldapConnectionOptions = new LdapConnectionOptions() .ConfigureClientCertificates(clientCertificates); Assert.Equal(clientCertificates, ldapConnectionOptions.ClientCertificates); }
public async Task Connect_with_no_ip_selected_throws() { var options = new LdapConnectionOptions() .ConfigureIpAddressFilter(ip => false); using var ldapConnection = new LdapConnection(options); await Assert.ThrowsAsync <ArgumentException>( "ipAddress", async() => await ldapConnection.ConnectAsync(TestsConfig.LdapServer.ServerAddress, TestsConfig.LdapServer.ServerPort)); }
public void Connect_with_ipv4_selected_connects() { var options = new LdapConnectionOptions() .ConfigureIpAddressFilter(ip => ip.AddressFamily == AddressFamily.InterNetwork); using var ldapConnection = new LdapConnection(options); ldapConnection.Connect(TestsConfig.LdapServer.ServerAddress, TestsConfig.LdapServer.ServerPort); Assert.True(ldapConnection.Connected); }
public void Connect_with_no_ip_selected_throws() { var options = new LdapConnectionOptions() .ConfigureIpAddressFilter(ip => false); using var ldapConnection = new LdapConnection(options); Assert.Throws <ArgumentException>( "ipAddress", () => ldapConnection.Connect(TestsConfig.LdapServer.ServerAddress, TestsConfig.LdapServer.ServerPort)); }
public async Task Connect_with_ipv6_selected_connects() { var options = new LdapConnectionOptions() .ConfigureIpAddressFilter(ip => ip.AddressFamily == AddressFamily.InterNetworkV6); using var ldapConnection = new LdapConnection(options); await ldapConnection.ConnectAsync(TestsConfig.LdapServer.ServerAddress, TestsConfig.LdapServer.ServerPort); Assert.True(ldapConnection.Connected); }
public async Task Connect_with_os_selected_ssl_protocol_connects() { var options = new LdapConnectionOptions() .UseSsl() .ConfigureIpAddressFilter(ip => ip.AddressFamily == AddressFamily.InterNetwork) .ConfigureRemoteCertificateValidationCallback((sender, certificate, chain, errors) => true) .ConfigureSslProtocols(SslProtocols.None); using var ldapConnection = new LdapConnection(options); await ldapConnection.ConnectAsync(TestsConfig.LdapServer.ServerAddress, TestsConfig.LdapServer.ServerPortSsl); }
public void UseIpAddressFilter_stores_always_false_filter() { bool AlwaysFalseIpAddressFilter(IPAddress ipAddress) => false; var ldapConnectionOptions = new LdapConnectionOptions() .ConfigureIpAddressFilter(AlwaysFalseIpAddressFilter); var ipAddressV4 = CreateRandomIpAddressV4(); Assert.Equal(AlwaysFalseIpAddressFilter(ipAddressV4), ldapConnectionOptions.IpAddressFilter(ipAddressV4)); var ipAddressV6 = CreateRandomIpAddressV6(); Assert.Equal(AlwaysFalseIpAddressFilter(ipAddressV6), ldapConnectionOptions.IpAddressFilter(ipAddressV6)); }
public ConnectWithClientCertificateTests() { _expectedAuthzId = "dn:cn=external-test,dc=example,dc=com"; _x509Certificate2 = new X509Certificate2( TestHelper.GetCertificate("external-test.pfx"), "password"); _ldapConnectionOptions = new LdapConnectionOptions() .ConfigureIpAddressFilter(ipAddress => ipAddress.AddressFamily == AddressFamily.InterNetwork) .ConfigureRemoteCertificateValidationCallback((sender, certificate, chain, errors) => true) .ConfigureLocalCertificateSelectionCallback(LdapConnectionLocalCertificateSelectionCallback) .ConfigureClientCertificates(new List <X509Certificate>() { _x509Certificate2, }); }
private static LdapConnectionOptions GetConnectionOptions() { var connectionOptions = new LdapConnectionOptions(); var configuration = LdapPlugin.Instance.Configuration; if (configuration.UseSsl) { connectionOptions.UseSsl(); } if (configuration.SkipSslVerify) { connectionOptions.ConfigureRemoteCertificateValidationCallback(LdapClient_UserDefinedServerCertValidationDelegate); } return(connectionOptions); }
public async Task Connect_with_obsolete_ssl_version_throws_on_connect() { #pragma warning disable CS0618 // Type or member is obsolete var options = new LdapConnectionOptions() .UseSsl() .ConfigureIpAddressFilter(ip => ip.AddressFamily == AddressFamily.InterNetwork) .ConfigureRemoteCertificateValidationCallback((sender, certificate, chain, errors) => true) .ConfigureSslProtocols(SslProtocols.Ssl2); #pragma warning restore CS0618 // Type or member is obsolete using var ldapConnection = new LdapConnection(options); // exception thrown is different on Windows vs Linux var exceptionThrowType = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? typeof(Win32Exception) : typeof(AuthenticationException); await Assert.ThrowsAsync( exceptionThrowType, async() => await ldapConnection.ConnectAsync(TestsConfig.LdapServer.ServerAddress, TestsConfig.LdapServer.ServerPortSsl)); }
public void New_instance_has_expected_defaults() { var ldapConnectionOptions = new LdapConnectionOptions(); Assert.False(ldapConnectionOptions.Ssl); var ipAddressV4 = CreateRandomIpAddressV4(); Assert.True(ldapConnectionOptions.IpAddressFilter(ipAddressV4)); var ipAddressV6 = CreateRandomIpAddressV6(); Assert.True(ldapConnectionOptions.IpAddressFilter(ipAddressV6)); Assert.Empty(ldapConnectionOptions.ClientCertificates); Assert.False(ldapConnectionOptions.CheckCertificateRevocationEnabled); Assert.Equal(SslProtocols.None, ldapConnectionOptions.SslProtocols); }
private static async Task <T> WithLdapConnectionImplAsync <T>(Func <ILdapConnection, Task <T> > funcOnConnectedLdapConnection, bool useSsl = false, bool disableEnvTransportSecurity = false) { var ldapConnectionOptions = new LdapConnectionOptions() .ConfigureIpAddressFilter(ipAddress => ipAddress.AddressFamily == AddressFamily.InterNetwork) .ConfigureRemoteCertificateValidationCallback((sender, certificate, chain, errors) => true); using (var ldapConnection = new LdapConnection(ldapConnectionOptions)) { var ldapPort = TestsConfig.LdapServer.ServerPort; var transportSecurity = GetTransportSecurity(useSsl, disableEnvTransportSecurity); if (transportSecurity == TransportSecurity.Ssl) { ldapConnection.SecureSocketLayer = true; ldapPort = TestsConfig.LdapServer.ServerPortSsl; } await ldapConnection.ConnectAsync(TestsConfig.LdapServer.ServerAddress, ldapPort); T retValue; if (transportSecurity == TransportSecurity.Tls) { try { await ldapConnection.StartTlsAsync(); retValue = await funcOnConnectedLdapConnection(ldapConnection); } finally { await ldapConnection.StopTlsAsync(); } } else { retValue = await funcOnConnectedLdapConnection(ldapConnection); } return(retValue); } }
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 ldapConnectionOptions = new LdapConnectionOptions(); if (_spineOptionsDelegate.CurrentValue.SdsUseLdaps) { ldapConnectionOptions.ConfigureSslProtocols(SecurityHelper.ParseTlsVersion(_spineOptionsDelegate.CurrentValue.SdsTlsVersion)); ldapConnectionOptions.UseSsl(); ldapConnectionOptions.ConfigureLocalCertificateSelectionCallback(SelectLocalCertificate); ldapConnectionOptions.ConfigureRemoteCertificateValidationCallback(ValidateServerCertificate); } using (var ldapConnection = new LdapConnection(ldapConnectionOptions) { ConnectionTimeout = _spineOptionsDelegate.CurrentValue.TimeoutMilliseconds }) { SetupMutualAuth(); ldapConnection.Connect(_spineOptionsDelegate.CurrentValue.SdsHostname, _spineOptionsDelegate.CurrentValue.SdsPort); 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; } }
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; } }