Check if MySqlConnection is using SSL

2019-08-25 16:47发布

I think my question is similar to C#: how to check if a MySqlConnection is using SSL or not?, but unfortunately it doesn't have good answers because it is unclear maybe. So here's my take:

I have created a new connection:

var connection = new MySqlConnection("Data Source=example.com;Port=3306;Database=Foo;User Id=root;Password=foo;SSL Mode=Required");

How do I verify it uses SSL, is there something like connection.IsOverSSL?

Edit:

I tried using SHOW SESSION STATUS LIKE 'Ssl_cipher', but this gives me Ssl_cipher even if SSL Mode=Required:

The code I use is:

var connection = new MySqlConnection(ConfigurationManager.AppSettings["Test"]);
connection.Open();
var command = new MySqlCommand("SHOW SESSION STATUS LIKE \'Ssl_cipher\'", connection);
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
    Console.WriteLine(reader.GetString(0));
}

According to https://dev.mysql.com/doc/refman/5.7/en/using-encrypted-connections.html, it should give me Ssl_cipher | DHE-RSA-AES128-GCM-SHA256

标签: c# mysql ssl
2条回答
ゆ 、 Hurt°
2楼-- · 2019-08-25 17:30

You can look at the connection string for the word "SSL". This would allow you to know if your IDbConnection is using ssl in this case. For a list of the connection strings that you could use with MySql, please visit ConnectionStrings.com. Let me know if this solves your problem.

I would try looking at the connection string. Here is a solution to demonstrate this.

var connStr = "Data Source=example.com;Port=3306;Database=Foo;User Id=root;Password=foo;SSL Mode=Required";
var sslElement = connStr.Split(';')
    .SingleOrDefault(s => s.StartsWith("SSL", StringComparison.InvariantCultureIgnoreCase));

var sslModeEnabled = (sslElement != null 
    && string.Equals(sslElement.Split('=')[1].Trim(), "None", StringComparison.InvariantCultureIgnoreCase) == false);


Console.WriteLine($"SSL Mode Enabled: {sslModeEnabled}");
查看更多
成全新的幸福
3楼-- · 2019-08-25 17:42

Turns out I wasn't printing the second column of the query, this now works:

var connection = new MySqlConnection(ConfigurationManager.AppSettings["Test"]);
connection.Open();
var command = new MySqlCommand("SHOW SESSION STATUS LIKE \'Ssl_cipher\'", connection);
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
    Console.WriteLine($"{reader.GetString(0)}: {reader.GetString(1)}");
}

It prints Ssl_cipher: AES256-SHA for SSL Mode=Required, and Ssl_cipher: for SSL Mode=None. On the other hand, I get Ssl_cipher: AES256-SHA even if SSL Mode is missing altogether so maybe it's on by default.

查看更多
登录 后发表回答