tencent cloud

Feedback

Setting SSL Encryption

Last updated: 2024-08-19 15:53:55

    SSL Encryption Overview

    Secure Sockets Layer (SSL) authentication is a process that authenticates the connection from the client to the TencentDB server. After SSL encryption is enabled, you can get a CA certificate and upload it to the server. Then, when the client accesses the database, the SSL protocol will be activated to establish an SSL secure channel between the client and the server to realize encrypted data transfer, prevent data from being intercepted, tampered with, and eavesdropped during the transfer, and ultimately ensure the data security for both the client and the server.
    The SSL protocol needs to be established based on the OSI Model - Transport Layer (TCP). Its advantage is that it is independent from application layer protocols; therefore, high-level application layer protocols such as HTTP, FTP, and TELNET can be transparently established on it. The SSL protocol completes encryption algorithm processing, communication key negotiation, and server authentication before communication is made through application layer protocols. After that, all data transferred through application layer protocols will be encrypted to ensure communication privacy.

    Background

    When you connect to a database in an unencrypted manner, all information transferred over the network will be in plaintext and may be eavesdropped, tampered with, and impersonated by illegal users. The SSL protocols are designed to address these risks and can bring the following benefits theoretically:
    Information is encrypted and cannot be eavesdropped by a third party.
    There is a verification mechanism for immediate tampering detection by both parties in the communication.
    Identity certificates will be used to authenticate the identity.
    TDSQL-C for MySQL supports enhancing link security by enabling SSL encryption and allows downloading and installing SSL CA certificates to the required application services.
    Note:
    SSL encryption protects the traffic between the database and the server rather than the data itself. Encrypting the network connection at the transport layer can improve the security and integrity of the communication data, but will increase the response time of the network connection.

    Prerequisites

    The instance version is MySQL 5.7/8.0.
    The instance form can be either pre-configured resources or Serverless.

    Supported Versions

    TDSQL-C for MySQL uses OpenSSL to implement secure connections. TDSQL-C for MySQL supports Transport Layer Security (TLS) versions 1.0, 1.1, 1.2, and 1.3. TLS support depends on the MySQL version. The table below shows the MySQL versions that support TLS.
    MySQL Version
    TLS1.0
    TLS1.1
    TLS1.2
    TLS1.3
    MySQL 5.7
    Not supported
    Not supported
    Supported
    Supported
    MySQL 8.0
    Supported
    Supported
    Supported
    Supported

    Enabling SSL Encryption

    1. Log in to the TDSQL-C for MySQL console, and click the cluster ID in the cluster list to enter the cluster management page.
    2. On the cluster management page, select the Data Security tab, and under SSL, select the read-write or read-only instance that requires enabling SSL encryption.
    
    3. This feature is disabled by default. Toggle the switch to on, and then click OK to enable SSL encryption.
    
    Note:
    During the process of enabling SSL encryption, your database instance will be restarted to load the SSL certificate. Make sure that your business has a reconnection mechanism.
    4. Click Download to download the SSL CA certificate, which is valid for 20 years. The downloaded file is a compressed package (TencentDB-SSL-CA.zip), containing the following three files:
    .p7b file: It is used to import the CA certificate into Windows.
    .jks file: It is a truststore certificate storage file in Java with a unified password 'tencentdb', used to import the CA certificate chain into the Java program.
    .pem file: It is used to import the CA certificate into other systems or applications.

    Configuring an SSL CA Certificate

    After enabling SSL encryption, you need to configure an SSL CA certificate when using a client to connect to TencentDB. The following takes Navicat as an example to describe how to install an SSL CA certificate. For other applications or clients, see their respective instructions.
    Note:
    Each time SSL encryption is enabled or disabled, a new certificate will be generated.
    1. Open Navicat.
    2. Right-click the target database and select Edit Connection.
    3. Select the SSL tab, and choose the path for the CA certificate in .pem format. After completing the settings, click OK.
    Note:
    If you encounter the 'connection is being used' error, it may be caused by a previous session that has not been disconnected. Close Navicat and try again.
    4. Double-click the target database to test whether the connection is normal.

    Disabling SSL Encryption

    1. Log in to the TDSQL-C for MySQL console, and click the cluster ID in the cluster list to enter the cluster management page.
    2. On the cluster management page, select the Data Security tab, and under SSL, select the read-write or read-only instance that requires disabling SSL encryption.
    3. Toggle the switch after Status to off, and in the pop-up prompt box, click OK.
    Note:
    During the process of disabling SSL encryption, your database instance will be restarted to uninstall the SSL certificate. Make sure that your business has a reconnection mechanism.

    Connecting to an Instance with SSL Encryption Enabled Using the MySQL Command Line Client

    If you are using a different version of the database, the connection command parameters of the MySQL client will vary. You can check the version of the database you are using with the following command, and then refer to the subsequent steps to connect to the instance.
    SELECT VERSION();
    
    Query result example:
    +--------------+
    | VERSION() |
    +--------------+
    | 8.0.30-txsql |
    +--------------+
    1 row in set (0.00 sec)
    1. Download the SSL CA certificate via the TDSQL-C for MySQL console. For the operation, see Enabling SSL Encryption.
    2. Use the MySQL Command Line Client to connect to an instance with SSL encryption enabled through command.
    For commands when the client-side database version is MySQL 5.7/8.0, connect to an instance using the following command.
    mysql -h <IP address> --ssl-ca=<CA certificate path> --ssl-mode=REQUIRED -P <Port number> -u <Username> -p
    If you want to use another SSL mode, such as VERIFY_CA or VERIFY_IDENTITY, connect to an instance using the following command.
    mysql -h <IP address> --ssl-ca=<CA certificate path> --ssl-mode=VERIFY_CA -P <Port number> -u <Username> -p
    Note:
    The --ssl-mode parameter indicates the SSL mode. Generally, it is recommended to use the REQUIRED and VERIFY_CA modes, which requires the MySQL client to connect to the MySQL server by using the SSL/TLS protocol and verification of the SSL/TLS certificate of the MySQL server. The VERIFY_IDENTITY mode, in addition to requiring verification of the MySQL server's SSL/TLS certificate, requires that the hostname used by the client should match the identity in the server certificate, otherwise the MySQL client will refuse to connect to the MySQL server.
    3. Enter the password of the corresponding username as prompted by the system.
    

    Sample Codes for Connecting to an SSL-enabled Instance for Common Programs

    PHP
    $conn = mysqli_init();
    mysqli_ssl_set($conn, NULL, NULL, "<Downloaded certificate path>", NULL, NULL);
    mysqli_real_connect($conn, '<Database access address>', '<Database access username>', '<Database access password>', '<Specified database to be accessed>', <Access port>, MYSQLI_CLIENT_SSL);
    if (mysqli_connect_errno($conn)) {
    die('Failed to connect to MySQL: '.mysqli_connect_error());
    }
    PHP (Using PDO)
    $options = array(
    PDO::MYSQL_ATTR_SSL_CA => '<Downloaded certificate path>'
    );
    $db = new PDO('mysql:host=<Database access address>;port=<Access port>;dbname=<Specified database to be accessed>', '<Database access username>', '<Database access password>', $options);
    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", "<Downloaded certificate path>");
    System.setProperty("javax.net.ssl.keyStorePassword","tencentdb");
    System.setProperty("javax.net.ssl.trustStore", "<Downloaded certificate path>");
    System.setProperty("javax.net.ssl.trustStorePassword","tencentdb");
    
    url = String.format("jdbc:mysql://%s/%s?serverTimezone=UTC&useSSL=true", '<Database access address>', '<Specified database to be accessed>');
    properties.setProperty("user", '<Database access username>');
    properties.setProperty("password", '<Database access password>');
    conn = DriverManager.getConnection(url, properties);
    .NET (MySqlConnector)
    var builder = new MySqlConnectionStringBuilder
    {
    Server = "<Database access address>",
    UserID = "<Database access username>",
    Password = "<Database access password>",
    Database = "<Specified database to be accessed>",
    SslMode = MySqlSslMode.VerifyCA,
    SslCa = "<Downloaded certificate>",
    };
    using (var connection = new MySqlConnection(builder.ConnectionString))
    {
    connection.Open();
    }
    Python (MySQLConnector Python)
    try:
    conn = mysql.connector.connect(user='<Database access username>',
    password='<Database access password>',
    database='<Specified database to be accessed>',
    host='<Database access address>',
    ssl_ca='<Downloaded certificate path>')
    except mysql.connector.Error as err:
    print(err)
    Python (PyMySQL)
    conn = pymysql.connect(user='<Database access username>',
    password='<Database access password>',
    database='<Specified database to be accessed>',
    host='<Database access address>',
    ssl={'ca': '<Downloaded certificate path>'})
    Django (PyMySQL)
    DATABASES = {
    'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': '<Specified database to be accessed>',
    'USER': '<Database access username>',
    'PASSWORD': '<Database access password>',
    'HOST': '<Database access address>',
    'PORT': '<Access port>',
    'OPTIONS': {
    'ssl': {'ca': '<Downloaded certificate path>'}
    }
    }
    }
    Node.js
    var fs = require('fs');
    var mysql = require('mysql');
    const serverCa = [fs.readFileSync("<Downloaded certificate path>", "utf8")];
    var conn=mysql.createConnection({
    host:"<Database access address>",
    user:"<Database access username>",
    password:"<Database access password>",
    database:"<Specified database to be accessed>",
    port:<Access port>,
    ssl: {
    rejectUnauthorized: true,
    ca: serverCa
    }
    });
    conn.connect(function(err) {
    if (err) throw err;
    });
    Golang
    rootCertPool := x509.NewCertPool()
    pem, _ := ioutil.ReadFile("<Downloaded certificate path>")
    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:<Access port>)/%s?allowNativePasswords=true&tls=custom","<Database access username>", "<Database access password>", "<Database access address>", '<Specified database to be accessed >')
    db, _ := sql.Open("mysql", connectionString)
    Ruby
    client = Mysql2::Client.new(
    :host => '<Database access address>',
    :username => '<Database access username>',
    :password => '<Database access password>',
    :database => '<Specified database to be accessed>',
    :sslca => '<Downloaded certificate path>'
    )
    
    
    Contact Us

    Contact our sales team or business advisors to help your business.

    Technical Support

    Open a ticket if you're looking for further assistance. Our Ticket is 7x24 avaliable.

    7x24 Phone Support