If you're 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 you're good to go with
authentication and encryption, but you would be wrong — this setting only enables encryption. You
must use VerifyFull if you want any type of 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 the connection in all cases.
- Required — always use SSL. Deny the connection if the server does not support SSL.
- VerifyCA — always use SSL. Validate the CA but tolerate a 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;
}