Using SSL/TLS with MySql in .Net

If your looking to use SSL/TLS with MySQL in .Net most tutorials will tell you to set the SSL Mode value in your connection string to Require.  This may make you think that you are good to go with authentication and encryption but you would be wrong.  This setting only enables encryption.  You must use VerifyFull if you want to add any type of authentication using certificate validation.

Connection string

Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;SSL Mode=VerifyFull;

SSL Mode has the following values:

  • None - do not use SSL.

  • Preferred - use SSL if the server supports it, but allow connection in all cases.

  • Required - Always use SSL. Deny connection if server does not support SSL.

  • VerifyCA - Always use SSL. Validate the CA but tolerate name mismatch.

  • VerifyFull - Always use SSL. Fail if the host name is not correct.

Here is the actual source code of the certificate validation override function.

private bool ServerCheckValidation(object sender, X509Certificate certificate,
                                              X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
      if (sslPolicyErrors == SslPolicyErrors.None)
        return true;

      if (Settings.SslMode == MySqlSslMode.Preferred ||
          Settings.SslMode == MySqlSslMode.Required)
      {
        //Tolerate all certificate errors.
        return true;
      }

      if (Settings.SslMode == MySqlSslMode.VerifyCA &&
          sslPolicyErrors == SslPolicyErrors.RemoteCertificateNameMismatch)
      {
        // Tolerate name mismatch in certificate, if full validation is not requested.
        return true;
      }

      return false;
}
Comments are closed