Skip to content

Commit

Permalink
fix: removing the certchainStore for tls
Browse files Browse the repository at this point in the history
  • Loading branch information
Nico-dl05 committed Dec 9, 2024
1 parent e665e57 commit fbdbdb6
Showing 1 changed file with 52 additions and 76 deletions.
128 changes: 52 additions & 76 deletions Adaptors/MongoDB/src/ServiceCollectionExt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Linq;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
Expand Down Expand Up @@ -49,8 +48,8 @@ public static class ServiceCollectionExt
{
[PublicAPI]
public static IServiceCollection AddMongoComponents(this IServiceCollection services,
ConfigurationManager configuration,
ILogger logger)
ConfigurationManager configuration,
ILogger logger)
{
services.AddMongoClient(configuration,
logger);
Expand All @@ -61,8 +60,8 @@ public static IServiceCollection AddMongoComponents(this IServiceCollection serv

[PublicAPI]
public static IServiceCollection AddMongoStorages(this IServiceCollection services,
ConfigurationManager configuration,
ILogger logger)
ConfigurationManager configuration,
ILogger logger)
{
logger.LogInformation("Configure MongoDB Components");

Expand Down Expand Up @@ -101,8 +100,8 @@ public static IServiceCollection AddMongoStorages(this IServiceCollection servic
}

public static IServiceCollection AddMongoClient(this IServiceCollection services,
ConfigurationManager configuration,
ILogger logger)
ConfigurationManager configuration,
ILogger logger)
{
Options.MongoDB mongoOptions;
services.AddOption(configuration,
Expand Down Expand Up @@ -169,82 +168,59 @@ public static IServiceCollection AddMongoClient(this IServiceCollection services
}

var settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
settings.AllowInsecureTls = mongoOptions.AllowInsecureTls;
settings.UseTls = mongoOptions.Tls;
settings.DirectConnection = mongoOptions.DirectConnection;
settings.Scheme = ConnectionStringScheme.MongoDB;
settings.MaxConnectionPoolSize = mongoOptions.MaxConnectionPoolSize;

// Configure the connection settings
settings.AllowInsecureTls = mongoOptions.AllowInsecureTls;
settings.UseTls = mongoOptions.Tls;
settings.DirectConnection = mongoOptions.DirectConnection;
settings.Scheme = ConnectionStringScheme.MongoDB;
settings.MaxConnectionPoolSize = mongoOptions.MaxConnectionPoolSize;
settings.ServerSelectionTimeout = mongoOptions.ServerSelectionTimeout;
settings.ReplicaSetName = mongoOptions.ReplicaSet;
settings.ReplicaSetName = mongoOptions.ReplicaSet;

if (!string.IsNullOrEmpty(mongoOptions.CAFile))
{
logger.LogInformation("Starting X509 certificate .");
logger.LogInformation("Starting X509 certificate configuration.");

// Find the authority certificate in the collection
// Load the CA certificate
var authority = new X509Certificate2(mongoOptions.CAFile);
logger.LogInformation("CA certificate loaded.: " + authority);
logger.LogInformation($"CA certificate loaded: {authority.Subject}");

// Configure the SSL settings
// SSL Parameters configuration
settings.SslSettings = new SslSettings
{
ClientCertificates = new X509Certificate2Collection(),
CheckCertificateRevocation = false,
EnabledSslProtocols = SslProtocols.Tls12,
ServerCertificateValidationCallback = (sender,
certificate2,
certChain,
sslPolicyErrors) =>
{
logger.LogInformation("Starting SSL certificate validation.");

if (sslPolicyErrors == SslPolicyErrors.None)
{
return true;
}

if ((sslPolicyErrors & ~SslPolicyErrors.RemoteCertificateChainErrors) != 0)
{
logger.LogError("SSL validation failed: {errors}",
sslPolicyErrors);
return false;
}

// If there is any error other than untrusted root or partial chain, fail the validation
if (certChain!.ChainStatus.Any(status
=> status.Status is not X509ChainStatusFlags.UntrustedRoot and
not X509ChainStatusFlags.PartialChain))
{
return false;
}

// Disable some extensive checks that would fail on the authority that is not in store
certChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
certChain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;

// Add unknown authority to the store
certChain.ChainPolicy.ExtraStore.Add(authority);

// Check if the chain is valid for the actual server certificate (ie: trusted)
if (!certChain.Build(new X509Certificate2(certificate2!)))
{
logger.LogError("SSL chain validation failed.");
return false;
}

// Check that the chain root is actually the specified authority (caCert)
var isTrusted =
certChain.ChainElements.Any(x => x.Certificate.Thumbprint == authority.Thumbprint);

if (!isTrusted)
{
logger.LogError("Certificate chain root does not match the specified CA authority.");
}

return isTrusted;
},
};
{
ClientCertificates = new X509Certificate2Collection(authority),
EnabledSslProtocols = SslProtocols.Tls12,
ServerCertificateValidationCallback = (sender,
certificate,
chain,
sslPolicyErrors) =>
{
logger.LogInformation("Validating server certificate.");


if (sslPolicyErrors == SslPolicyErrors.None)
{
logger.LogInformation("SSL validation successful: no errors.");
return true;
}

logger.LogError($"SSL validation failed with errors: {sslPolicyErrors}");

// Refuse critical errors
if ((sslPolicyErrors & ~SslPolicyErrors.RemoteCertificateChainErrors) != 0)
{
logger.LogError("Critical SSL errors detected.");
return false;
}

logger.LogInformation("SSL validation succeeded despite minor chain errors.");
return true;
},
};
}


settings.ClusterConfigurator = cb =>
{
//cb.Subscribe<CommandStartedEvent>(e => logger.LogTrace("{CommandName} - {Command}",
Expand Down Expand Up @@ -278,7 +254,7 @@ public static IServiceCollection AddMongoClient(this IServiceCollection services
/// <returns>Services</returns>
[PublicAPI]
public static IServiceCollection AddClientSubmitterAuthenticationStorage(this IServiceCollection services,
ConfigurationManager configuration)
ConfigurationManager configuration)
{
var components = configuration.GetSection(Components.SettingSection);
if (components[nameof(Components.AuthenticationStorage)] == "ArmoniK.Adapters.MongoDB.AuthenticationTable")
Expand All @@ -299,7 +275,7 @@ public static IServiceCollection AddClientSubmitterAuthenticationStorage(this IS
/// <returns>Services</returns>
[PublicAPI]
public static IServiceCollection AddClientSubmitterAuthServices(this IServiceCollection services,
ConfigurationManager configuration,
ConfigurationManager configuration,
out AuthenticationCache authCache)
{
authCache = new AuthenticationCache();
Expand Down

0 comments on commit fbdbdb6

Please sign in to comment.