MongoDB SSL with self-signed certificates in C#
Tags: mongodb, ssl, database
Published: 2020-11-04 16:15:57

---
title: MongoDB SSL with self-signed certificates in C#
published: true
description: A simple guide on how to connect MongoDB SSL to your C# Application using Self-Signed Certificates for maximum security and availability.
tags: MongoDB, SSL, Databases, Database
//cover_image: https://scalegrid.io/blog/wp-content/uploads/2020/09/MongoDB-SSL-with-self-signed-certificates-in-C-blog.jpg
---
<link rel="canonical" href="https://scalegrid.io/blog/mongodb-ssl-with-self-signed-certificates-in-c/" />

<p style="text-align: justify">When deploying MongoDB in production, it is strongly recommended that you use an SSL-enabled <a style="color: #2da964" href="https://scalegrid.io/blog/geo-distributed-mongodb-replica-sets-for-100-uptime/">geo-distributed replica-set</a> configuration for maximum security and availability. ScaleGrid provides you two options for setting up SSL.</p>

<p style="text-align: justify">One option is purchasing your own CA-signed SSL certificates and configuring them on the <a style="color: #2da964" href="https://scalegrid.io/mongodb.html">MongoDB server</a>. If your application connects to the production database over a public network, do reach out to <a style="color: #2da964" href="mailto:support@scalegrid.io">support@scalegrid.io</a> to learn more about this.</p>

<p style="text-align: justify">But by default, we configure <a style="color: #2da964" href="https://en.wikipedia.org/wiki/Self-signed_certificate">self-signed certificates</a> for SSL when creating nodes for a new cluster. This avoids extra costs, and can be equally secure when correctly configured. But this does mean that your MongoDB driver needs some help to validate the <a style="color: #2da964" href="https://knowledge.digicert.com/solution/SO16297.html">certificate chain</a>.</p>

<p style="text-align: justify">When handling self-signed certificates, some developers circumvent validation all-together, and seriously compromise security! In this blog post, we show you two methods to securely connect to a MongoDB server configured with self-signed certificates for SSL, using the <a style="color: #2da964" href="https://docs.mongodb.com/drivers/csharp">official C# MongoDB driver</a>. With a few simple steps, you can provide your driver the information it needs to validate the server certificate and keep the connection secure.</p>

<h2 style="padding-top: 15px">Prerequisites</h2>

<p style="text-align: justify">Before you proceed,</p>
<ul>
	<li>Make sure your application can connect to your ScaleGrid deployment. Please refer to our <a style="color: #2da964" href="https://help.scalegrid.io/docs/mongodb-connecting-to-your-application">MongoDB Connections help doc</a> to review the general steps for connecting your application to a ScaleGrid deployment.</li>
	<li>You need to have the <a style="color: #2da964" href="https://mongodb.github.io/mongo-csharp-driver/2.10/getting_started/installation/">MongoDB Driver installed</a>. Please refer to the <a style="color: #2da964" href="https://mongodb.github.io/mongo-csharp-driver/2.8/getting_started/">MongoDB Driver docs</a> to review the steps for installing and using the C# MongoDB.Driver.</li>
</ul>

<p style="text-align: justify">Note: All the code samples have been tested using MongoDB Driver v2.8.1 along with .NET Framework v4.6.1. However, they should work on any reasonably recent version of .NET Framework and MongoDB Driver.</p>

<table style="margin-top: 15px" width="100%">
<tbody>
<tr>
<td style="padding: 15px;background: #def5fe">
<span style="font-size: 18px">
<h3>&#128679; Remember to... </h3>
<hr>
<b>Modify the file paths and connection URLs in the code samples to your own file paths and URLs. Else the code samples will not work. Please see the bold parts of the code samples for where you need to make changes.</b>

For example:
<ul>
<li><b>&lt;path-to-downloaded-CA-Cert.cer&gt;</b> = C:\Users\User\Folder\caCert.cer</li>
<li><b>&lt;host1&gt;</b> = mongodb://admin:<password>@SG-example.servers.example.com:27017</li>
</ul>
</span></td>
</tr>
</tbody>
</table>

<h2 style="padding-top: 15px">Method 1: Adding the ScaleGrid Certificate to Windows Trust Store</h2>

<p style="text-align: justify">One of the simplest ways of using self-signed certificates with C# and the .NET Framework is adding the certificate as “Trusted Root” on the Windows Trust Store. Here’s how you can do it:</p>

<ol>
	<li><a style="color: #2da964" href="https://help.scalegrid.io/docs/mongodb-connecting-to-your-application#section-connecting-to-ssl-enabled-clusters">Download your CA Certificate</a> from the ScaleGrid UI.</li>
	<li>Open a PowerShell Prompt - if you wish to add the certificate as trusted-root for all users, you will have to open it in administrative mode.</li>
	<li>Execute the following command, or do this using the <a style="color: #2da964" href="https://support.globalsign.com/customer/en/portal/articles/1217281-import-and-export-certificate---microsoft-windows">Microsoft Management Console</a>.:
	<ul>
		<li>To add only for the current user:</li>
	</ul>
<pre><code>Import-Certificate -FilePath <b>&lt;path-to-downloaded-CA-Cert.cer&gt;</b> -CertStoreLocation 'Cert:\CurrentUser\Root'</code></pre>
	<ul>
		<li>To add for everyone:</li>
	</ul>
<pre><code>Import-Certificate -FilePath <b>&lt;path-to-downloaded-CA-Cert.cer&gt;</b> -CertStoreLocation Cert:\LocalMachine\Root'</code></pre>
	</li>
</ol>

<p style="text-align: justify">That’s it! Now the self-signed certificate will pass all default validations, and you are ready to create a MongoDB client.</p>

<pre><code>var connURL = "mongodb://admin:<b>&lt;password&gt;</b>@<b>&lt;host1&gt;</b>,<b>&lt;host2&gt;</b>:27017/admin?replicaSet=<b>&lt;ReplicaSetName&gt;</b>&amp;ssl=true";
var client = new MongoClient(connURL);</code></pre>

<h2 style="padding-top: 15px">Method 2: Using Custom Validation Callback</h2>

<p style="text-align: justify">There are two problems with adding the ScaleGrid Certificate to the Windows Trust Store:</p>

<ul>
	<li>The settings apply to all programs running on the machine: this can be a security vulnerability.</li>
	<li>This has to be done once per-machine. If you move your code to a new server, it can suddenly stop working. This leaves the method prone to human error.</li>
</ul>

<p style="text-align: justify">Hence, the recommended way to connect using self-signed certificates is to use a custom validation callback that verifies the certificate. Here’s how you can do this:</p>

<ol>
	<li><a style="color: #2da964" href="https://help.scalegrid.io/docs/mongodb-connecting-to-your-application#section-connecting-to-ssl-enabled-clusters">Download your CA Certificate</a> and save it to a location your application can access (this will typically be its data directory).</li>
	<li>From your application, you can read this certificate and match the one you receive from the MongoDB Server.</li>
	<li>Alternatively, you can store a cryptographic hash of the certificate. Instead of reading the certificate and matching, you can <a style="color: #2da964" href="https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.hashalgorithm?view=netframework-4.6">compute the cryptographic hash</a> over the received certificate and match the results.</li>
</ol>

<p style="text-align: justify">Here’s a sample program that has the CA Certificate stored under its bin directory with the name caCert.cer. It simply prints out a list of all databases that exist on the MongoDB Server:</p>
<pre><code>
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace TestMongoDB
{
  class Program
  {
    static void Main(string[] args)
    {
      var connURL = "mongodb:<b>&lt;password&gt;</b>//admin:@<b>&lt;host1&gt;</b>,<b>&lt;host2&gt;</b>:27017/admin?replicaSet=<b>&lt;Replica-Set-Name&gt;</b>&amp;ssl=true";
      var clientSettings = MongoClientSettings.FromUrl(new MongoUrl(connURL));
      clientSettings.UseSsl = true;
      clientSettings.VerifySslCertificate = true;
      clientSettings.SslSettings = new SslSettings();
      clientSettings.SslSettings.ServerCertificateValidationCallback = ValidateServerCertficate;
      var client = new MongoClient(clientSettings);
      using (IAsyncCursor cursor = client.ListDatabases())
      {
        while (cursor.MoveNext())
        {
          foreach (var doc in cursor.Current)
          {
            Console.WriteLine(doc["name"]); // database name
          }
        }
      }
    }

    private static bool ValidateServerCertficate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
      bool certMatch = false; // Assume failure
      switch(sslPolicyErrors)
      {
        case SslPolicyErrors.None:
          Console.WriteLine("No validation errors - accepting certificate");
          certMatch = true;
          break;
        case SslPolicyErrors.RemoteCertificateChainErrors:
          Console.WriteLine("Failed to validate certificate chain. Most likely a self-signed certificate");
          if (chain.ChainElements.Count == 1 &amp;&amp; chain.ChainStatus[0].Status == X509ChainStatusFlags.UntrustedRoot) //It is a self-signed certificate, so chain length will be 1.
          {
            X509Certificate savedCert = X509Certificate.CreateFromCertFile("caCert.cer");
            if (savedCert.Equals(cert)) //This verifies that the issuer and serial number matches. You can also use a cryptographic hash, or match the two certificates byte by byte.
            {
              Console.WriteLine("The certificates match");
              certMatch = true;
            }
          }
          break;
        default:
          Console.WriteLine("Name mismatch or remote-cert not available. Rejecting connection");
          break;
      }
      return certMatch;
    }
  }
}</code></pre>

<h2 style="padding-top: 15px"> Troubleshooting </h2>

<p style="text-align: justify">If you’re having trouble connecting to your SSL-enabled MongoDB deployment, here are a few tips for debugging:</p>

<ul>
	<li>First, verify that you can actually connect to the MongoDB server from the server where your application is running. The simplest way to do this is to <a style="color: #2da964" href="https://docs.mongodb.com/manual/installation/#mongodb-community-edition">install mongo shell</a> on the client machine. On Linux, you wouldn’t need to install the entire MongoDB server – you can choose to install just the shell. Once the shell is available, try to use the ‘<a style="color: #2da964" href="https://help.scalegrid.io/docs/mongodb-command-line-syntax#connect-using-the-mongo-shell">Command Line Syntax</a>’ we provide to attempt to connect to the server.</li>

	<li>If you are unable to connect via the mongo shell, it means that the client machine is unable to reach the port 27017 of the MongoDB servers. Look at your Security Group, VPC, and/or ScaleGrid firewall settings to ensure that there is connectivity between the client and server machines.</li>

	<li>If network connectivity is correct, the next thing to check is that you are using <a style="color: #2da964" href="https://docs.mongodb.com/ecosystem/drivers/driver-compatibility-reference/#c-net-driver-compatibility">versions of MongoDB Driver</a> and <a style="color: #2da964" href="https://docs.mongodb.com/ecosystem/drivers/csharp/#language-compatibility">.NET Framework</a> that are compatible with the version of your MongoDB server.</li>

	<li>If you have confirmed that the driver versions are correct, try running a sample C# program in debug mode, similar to the example we provided above. A step-by-step execution would help root cause the problem.</li>

	<li>If you are still having trouble connecting to your instance, please reach out to us at <a style="color: #2da964" href="mailto:support@scalegrid.io">support@scalegrid.io</a> with detailed results of the above troubleshooting steps and with the exact versions of C# and the Mongo Driver you are using.</li>
</ul>

<p style="text-align: justify">If you are new to ScaleGrid and want to give this tutorial a try, sign up for a <a style="color: #2da964" href="https://scalegrid.io/">free 30-day trial</a> to explore the platform and test out connecting MongoDB to your C# application.</p>