配置应用程序的 SSL 连接性以安全连接到 Azure Database for MySQLConfigure SSL connectivity in your application to securely connect to Azure Database for MySQL

备注

将要查看的是 Azure Database for MySQL 的新服务。You are viewing the new service of Azure Database for MySQL. 若要查看经典 MySQL Database for Azure 的文档,请访问此页To view the documentation for classic MySQL Database for Azure, please visit this page.

Azure Database for MySQL 支持使用安全套接字层 (SSL) 将 Azure Database for MySQL 服务器连接到客户端应用程序。Azure Database for MySQL supports connecting your Azure Database for MySQL server to client applications using Secure Sockets Layer (SSL). 通过在数据库服务器与客户端应用程序之间强制实施 SSL 连接,可以加密服务器与应用程序之间的数据流,有助于防止“中间人”攻击。Enforcing SSL connections between your database server and your client applications helps protect against "man in the middle" attacks by encrypting the data stream between the server and your application.

步骤 1:获取 SSL 证书Step 1: Obtain SSL certificate

https://www.digicert.com/CACerts/DigiCertGlobalRootCA.crt 下载通过 SSL 与 Azure Database for MySQL 服务器通信所需的证书,再将证书文件保存到本地驱动器(例如,本教程使用 c:\ssl)。Download the certificate needed to communicate over SSL with your Azure Database for MySQL server from https://www.digicert.com/CACerts/DigiCertGlobalRootCA.crt and save the certificate file to your local drive (this tutorial uses c:\ssl for example).

步骤 2:下载并安装 OpenSSLStep 2: Download and install OpenSSL

下载页查找并下载最新版本的 OpenSSL。Find and download the latest version of OpenSSL from the downloads page.

步骤 3:将本地证书文件移到 OpenSSL 目录Step 3: Move the local certificate file to the OpenSSL directory

将步骤 1 中下载的证书放入 ...\OpenSSL-Win32\bin 目录。Put the certificate downloaded in step 1 into the ...\OpenSSL-Win32\bin directory.

步骤 4:将证书文件转换为 PEM 格式Step 4: Convert the certificate file to PEM format

下载的根证书文件采用 crt 格式。The downloaded root certificate file is in the crt format. 需要使用 openssl.exe 命令行工具执行以下命令来转换文件格式:You need to use the openssl.exe command line tool to execute the following commands to convert the file format:

OpenSSL>x509 -inform DEV -in DigiCertGlobalRootCA.crt -out DigiCertGlobalRootCA.pem

步骤 5:绑定 SSLStep 5: Bind SSL

使用 MySQL Workbench 通过 SSL 连接到服务器Connecting to server using the MySQL Workbench over SSL

配置 MySQL Workbench,以便安全地通过 SSL 连接。Configure the MySQL Workbench to connect securely over SSL. 从“设置新连接”对话框,导航到“SSL”选项卡。在“SSL CA 文件:”字段中输入 DigiCertGlobalRootCA.pem 的文件位置。From the Setup New Connection dialogue, navigate to the SSL tab. In the SSL CA File: field, enter the file location of the DigiCertGlobalRootCA.pem. 保存 SSL 配置Save SSL configuration

对于现有连接,可以通过右键单击“连接”图标并选择“编辑”来绑定 SSL。For existing connections, you can bind SSL by right-clicking on the connection icon and choose edit. 然后导航到“SSL”选项卡,并绑定证书文件。Then navigate to the SSL tab and bind the cert file.

使用 MySQL CLI 通过 SSL 连接到服务器Connecting to server using the MySQL CLI over SSL

绑定 SSL 证书的另一种方法是使用 MySQL 命令行接口执行以下命令。Another way to bind the SSL certificate is to use the MySQL command-line interface by executing the following commands.

mysql.exe -h mydemoserver.mysql.database.chinacloudapi.cn -u Username@mydemoserver -p --ssl-mode=REQUIRED --ssl-ca=C:\OpenSSL-Win32\bin\DigiCertGlobalRootCA.pem

备注

在 Windows 上使用 MySQL 命令行接口时,可能会收到错误 SSL connection error: Certificate signature check failedWhen using the MySQL command-line interface on Windows, you may receive an error SSL connection error: Certificate signature check failed. 如果发生这种情况,请将 --ssl-mode=REQUIRED --ssl-ca={filepath} 参数替换为 --sslIf this occurs, replace the --ssl-mode=REQUIRED --ssl-ca={filepath} parameters with --ssl.

步骤 6:在 Azure 中强制实施 SSL 连接Step 6: Enforcing SSL connections in Azure

使用 Azure 门户Using the Azure portal

在 Azure 门户中,访问 Azure Database for MySQL 服务器,并单击“连接安全性”。Using the Azure portal, visit your Azure Database for MySQL server, and then click Connection security. 使用切换按钮来启用或禁用“强制实施 SSL 连接”设置,并单击“保存” 。Use the toggle button to enable or disable the Enforce SSL connection setting, and then click Save. Azure 建议你始终启用“强制实施 SSL 连接”设置,以增强安全性。Azure recommends to always enable the Enforce SSL connection setting for enhanced security. enable-sslenable-ssl

使用 Azure CLIUsing Azure CLI

可以通过在 Azure CLI 中分别使用“Enabled”或“Disabled”值来启用或禁用“ssl-enforcement”参数。You can enable or disable the ssl-enforcement parameter by using Enabled or Disabled values respectively in Azure CLI.

az mysql server update --resource-group myresource --name mydemoserver --ssl-enforcement Enabled

步骤 7:验证 SSL 连接Step 7: Verify the SSL connection

执行 mysql status 命令,验证是否已使用 SSL 连接到 MySQL 服务器:Execute the mysql status command to verify that you have connected to your MySQL server using SSL:

mysql> status

查看输出以确认连接是否已加密,如果已加密,输出应显示为:“SSL: 使用中的密码为 AES256-SHA”Confirm the connection is encrypted by reviewing the output, which should show: SSL: Cipher in use is AES256-SHA

代码示例Sample code

若要从应用程序通过 SSL 与 Azure Database for MySQL 建立安全连接,请参阅以下代码示例:To establish a secure connection to Azure Database for MySQL over SSL from your application, refer to the following code samples:

请参阅 Azure Database for MySQL 服务支持的兼容驱动程序列表。Refer to the list of compatible drivers supported by the Azure Database for MySQL service.

PHPPHP

$conn = mysqli_init();
mysqli_ssl_set($conn,NULL,NULL, "C:\OpenSSL-Win32\bin\DigiCertGlobalRootCA.pem", NULL, NULL) ; 
mysqli_real_connect($conn, 'mydemoserver.mysql.database.chinacloudapi.cn', 'myadmin@mydemoserver', 'yourpassword', 'quickstartdb', 3306, MYSQLI_CLIENT_SSL);
if (mysqli_connect_errno($conn)) {
die('Failed to connect to MySQL: '.mysqli_connect_error());
}

PHP(使用 PDO)PHP (Using PDO)

$options = array(
    PDO::MYSQL_ATTR_SSL_CA => 'C:\OpenSSL-Win32\bin\DigiCertGlobalRootCA.pem'
);
$db = new PDO('mysql:host=mydemoserver.mysql.database.chinacloudapi.cn;port=3306;dbname=databasename', 'username@mydemoserver', 'yourpassword', $options);

Python (MySQLConnector Python)Python (MySQLConnector Python)

try:
    conn = mysql.connector.connect(user='myadmin@mydemoserver',
                                   password='yourpassword',
                                   database='quickstartdb',
                                   host='mydemoserver.mysql.database.chinacloudapi.cn', 
                                   ssl_ca='C:\OpenSSL-Win32\bin\DigiCertGlobalRootCA.pem')
except mysql.connector.Error as err:
    print(err)

Python (PyMySQL)Python (PyMySQL)

conn = pymysql.connect(user='myadmin@mydemoserver',
                       password='yourpassword',
                       database='quickstartdb',
                       host = 'mydemoserver.mysql.database.chinacloudapi.cn', 
                       ssl = {'ssl': {'ssl-ca': 'C:\OpenSSL-Win32\bin\DigiCertGlobalRootCA.pem'}})

Django (PyMySQL)Django (PyMySQL)

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'quickstartdb',
        'USER': 'myadmin@mydemoserver',
        'PASSWORD': 'yourpassword',
        'HOST': 'mydemoserver.mysql.database.chinacloudapi.cn',
        'PORT': '3306',
        'OPTIONS': {
            'ssl': {'ssl-ca': 'C:\OpenSSL-Win32\bin\DigiCertGlobalRootCA.pem'}
        }
    }
}

RubyRuby

client = Mysql2::Client.new(
        :host     => 'mydemoserver.mysql.database.chinacloudapi.cn', 
        :username => 'myadmin@mydemoserver',
        :password => 'yourpassword',
        :database => 'quickstartdb',
        :ssl_ca => 'C:\OpenSSL-Win32\bin\DigiCertGlobalRootCA.pem'
    )

GolangGolang

rootCertPool := x509.NewCertPool()
pem, _ := ioutil.ReadFile("C:\OpenSSL-Win32\bin\DigiCertGlobalRootCA.pem")
if ok := rootCertPool.AppendCertsFromPEM(pem); !ok {
    log.Fatal("Failed to append PEM.")
}
mysql.RegisterTLSConfig("custom", &tls.Config{RootCAs: rootCertPool})
var connectionString string
connectionString = fmt.Sprintf("%s:%s@tcp(%s:3306)/%s?allowNativePasswords=true&tls=custom",'myadmin@mydemoserver' , 'yourpassword', 'mydemoserver.mysql.database.chinacloudapi.cn', 'quickstartdb')    
db, _ := sql.Open("mysql", connectionString)

Java(适用于 Java 的 MySQL 连接器)Java (MySQL Connector for Java)

# generate truststore and keystore in code
String importCert = " -import "+
    " -alias mysqlServerCACert "+
    " -file " + ssl_ca +
    " -keystore truststore "+
    " -trustcacerts " + 
    " -storepass password -noprompt ";
String genKey = " -genkey -keyalg rsa " +
    " -alias mysqlClientCertificate -keystore keystore " +
    " -storepass password123 -keypass password " + 
    " -dname CN=MS ";
sun.security.tools.keytool.Main.main(importCert.trim().split("\\s+"));
sun.security.tools.keytool.Main.main(genKey.trim().split("\\s+"));

# use the generated keystore and truststore 
System.setProperty("javax.net.ssl.keyStore","path_to_keystore_file");
System.setProperty("javax.net.ssl.keyStorePassword","password");
System.setProperty("javax.net.ssl.trustStore","path_to_truststore_file");
System.setProperty("javax.net.ssl.trustStorePassword","password");

url = String.format("jdbc:mysql://%s/%s?serverTimezone=UTC&useSSL=true", 'mydemoserver.mysql.database.chinacloudapi.cn', 'quickstartdb');
properties.setProperty("user", 'myadmin@mydemoserver');
properties.setProperty("password", 'yourpassword');
conn = DriverManager.getConnection(url, properties);

Java(适用于 Java 的 MariaDB 连接器)Java (MariaDB Connector for Java)

# generate truststore and keystore in code
String importCert = " -import "+
    " -alias mysqlServerCACert "+
    " -file " + ssl_ca +
    " -keystore truststore "+
    " -trustcacerts " + 
    " -storepass password -noprompt ";
String genKey = " -genkey -keyalg rsa " +
    " -alias mysqlClientCertificate -keystore keystore " +
    " -storepass password123 -keypass password " + 
    " -dname CN=MS ";
sun.security.tools.keytool.Main.main(importCert.trim().split("\\s+"));
sun.security.tools.keytool.Main.main(genKey.trim().split("\\s+"));

# use the generated keystore and truststore 
System.setProperty("javax.net.ssl.keyStore","path_to_keystore_file");
System.setProperty("javax.net.ssl.keyStorePassword","password");
System.setProperty("javax.net.ssl.trustStore","path_to_truststore_file");
System.setProperty("javax.net.ssl.trustStorePassword","password");

url = String.format("jdbc:mariadb://%s/%s?useSSL=true&trustServerCertificate=true", 'mydemoserver.mysql.database.chinacloudapi.cn', 'quickstartdb');
properties.setProperty("user", 'myadmin@mydemoserver');
properties.setProperty("password", 'yourpassword');
conn = DriverManager.getConnection(url, properties);

.NET (MySqlConnector).NET (MySqlConnector)

var builder = new MySqlConnectionStringBuilder
{
    Server = "mydemoserver.mysql.database.chinacloudapi.cn",
    UserID = "myadmin@mydemoserver",
    Password = "yourpassword",
    Database = "quickstartdb",
    SslMode = MySqlSslMode.VerifyCA,
    CACertificateFile = "C:\OpenSSL-Win32\bin\DigiCertGlobalRootCA.pem",
};
using (var connection = new MySqlConnection(builder.ConnectionString))
{
    connection.Open();
}

后续步骤Next steps

Connection libraries for Azure Database for MySQL(Azure Database for MySQL 的连接库)中查看各种应用程序连接性选项Review various application connectivity options following Connection libraries for Azure Database for MySQL