Home > other >  Problem with connect to mongoDB use tls certifications
Problem with connect to mongoDB use tls certifications

Time:08-28


I have a problem with connection string to database.
I have a server with mongodb, who are configure to connect with tls.

My connection string look like:
mongodb://{mongodbusername}:{mongodbpassword}@{mongodburi}:27017/someDatabase?authMechanism=DEFAULT&authSource=admin&tls=true&tlsCAFile=<path>/rootCA.pem&tlsCertificateKeyFile=<path>/mongodb.pem&tlsAllowInvalidCertificates=true&tls=true

During starting program, he is transfrom to:
mongodb://username:password@url:27017/someDB?authMechanism=DEFAULT&authSource=admin&tls=true&tlsCAFile=C:/certs/rootCA.pem&tlsCertificateKeyFile=C:/certs/mongodb.pem&tlsAllowInvalidCertificates=true&tls=true

I try path like C:\certs\ too.

Trying connect to database I get error like this:
Message=A timeout occurred after 30000ms selecting a server using CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 }, OperationsCountServerSelector }. Client view of cluster state is { ClusterId : "1", Type : "Unknown", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId : 1, EndPoint : "Unspecified/path:27017" }", EndPoint: "Unspecified/path:27017", ReasonChanged: "Heartbeat", State: "Disconnected", ServerVersion: , TopologyVersion: , Type: "Unknown", HeartbeatException: "MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid because of errors in the certificate chain: UntrustedRoot

When I try connect to mongoDB instance via mongodb compass with this same credential and that same certs, everythink are ok and I will be connected do instance.

Can you help me?

CodePudding user response:

.net driver doesn't support providing certificates via connection string. To provide a client certificate, you need to use ClientCertificates list in SslSettings. As for CA certificate, you only can configure it on OS level. For windows, it can be done via certutil:

certutil.exe -addstore "Root" <path_to_ca_cert>

Also, a client certificate should be in .p12 format, not .pem. To convert pem certificate into p12, you can use openssl:

openssl pkcs12 -export -in "${CLIENT_PEM}" -out "${X509_CLIENT_P12}" \
-name "Client Certificate" \
-password "pass:${X509_CLIENT_CERTIFICATE_PASSWORD}"

CodePudding user response:

You need to add whatever certificate IIS is using to your Trusted Root Certification Authorities stored on your local computer.

A workaround to bypass this is disabling the certificate validation, but I wouldn't recommend this as a long term solution:

var client = new MongoClient();
client.Settings.VerifySslCertificate = false;
  • Related