Chris Marisic
Chris Marisic

Reputation: 33108

How to connect to a server via TLS using MongoDB.Driver with a certificate file?

According to the MongoDB documentation it is supposed to be possible to connect via TLS where you specify the pem certificate by the tlsCAFile parameter.

However I have not been able to use the client in such a manner that it is successful.

[Installing the certificate to the local store is NOT an option]

All the client provides as an error is a generic A timeout occured after 30000ms... + The remote certificate is invalid according to the validation procedure regardless of what I've done. I have verified the server is accessible by MongoDB administrative tools by providing the cert explicitly to them.

Upvotes: 2

Views: 1912

Answers (2)

Mesut Ucar
Mesut Ucar

Reputation: 11

I've had the same problem while connecting to AWS-DocumentDB (that's compatible with MongoDB) and after struggling a few hours, Chris's answer worked perfectly.

I've just made a minor change just to verify if the certificate issuer is Amazon.

clientSettings.SslSettings = new SslSettings
{
    EnabledSslProtocols = SslProtocols.Tls11,
    ServerCertificateValidationCallback = (sender, certificate, chain, errors) =>
        certificate.Issuer.Contains("CN=Amazon")
};

Upvotes: 1

Chris Marisic
Chris Marisic

Reputation: 33108

Eventually stumbled upon a solution to this:

var clientSettings = MongoClientSettings.FromUrl(new MongoUrl(mongoUrl));

clientSettings.UseTls = true;
clientSettings.SslSettings = new SslSettings
{
    EnabledSslProtocols = SslProtocols.Tls11,
    ServerCertificateValidationCallback = (sender, certificate, chain, errors) =>
        certificate.Subject.Contains("O=myOU,")
};

This is a looser validation but good enough for my needs. You could go with no-validation with => true or for full validation you could load the certificate into memory and verify the thumbprints match along with expiration dates being valid.

Upvotes: 2

Related Questions