How to enable SSL/TLS for MySQL server and client(如何设置MySQL服务器和客户端加密传输以及对应Django应用的设置)

首先看一下服务器版本,如果不同版本请自行迁移

ubuntu 16.04 visit here

Server version: 5.6.19-0ubuntu0.14.04.1 (Ubuntu)

mysql> status
--------------
mysql  Ver 14.14 Distrib 5.6.19, for debian-linux-gnu (x86_64) using  EditLine wrapper


Current database:   

SSL:            Cipher in use is DHE-RSA-AES256-SHA##这是设置后的显示
#这是未设置前的现实SSL:          Not in use

Current pager:      stdout
Using outfile:      ''
Using delimiter:    ;
Server version:     5.6.19-0ubuntu0.14.04.1 (Ubuntu)
Protocol version:   10
Connection:     Localhost via UNIX socket
Server characterset:    latin1
Db     characterset:    latin1
Client characterset:    utf8
Conn.  characterset:    utf8
UNIX socket:        /var/run/mysqld/mysqld.sock
Uptime:         2 hours 17 min 44 sec

参考此文How to enable SSL for MySQL server and client,然后自己踩了一些坑完成了此功能,本文主要记录一下大体步骤以及出现的问题

首先是加密算法的选择:

I suggest using -sha256 for SHA-1 is no longer considered suitable for SSL/TLS certificates.

step 1:生成服务器端加密配置

#create the CA private key and certificate.
openssl genrsa 2048 > ca-key.pem
openssl req -sha256 -new -x509 -nodes -days 3650 -key ca-key.pem > ca-cert.pem

openssl req -sha256 -newkey rsa:2048 -days 730 -nodes -keyout server-key.pem > server-req.pem
openssl rsa -in server-key.pem -out server-key.pem
openssl x509 -sha256 -req -in server-req.pem -days 730 -CA ca-cert.pem -CAkey ca-key.pem -set_serial 01 > server-cert.pem


mysql> GRANT ALL PRIVILEGES ON *.* TO 'bi'@'%' IDENTIFIED BY 'biwahaha' REQUIRE SSL;

how to remove SSL REQUIRE:
mysql> UPDATE mysql.user SET ssl_type = '' WHERE ssl_type = 'any' ; FLUSH PRIVILEGES;

step 2: 配置mysql, my.cnf

ssl-ca=/etc/mysql/ca-cert.pem
ssl-cert=/etc/mysql/server-cert.pem
ssl-key=/etc/mysql/server-key.pem
#配置完成记得重启服务
$ sudo service mysql restart
or:

$ sudo systemctl restart mysql
or:

$ sudo /etc/init.d/mysql restart

没有配置前下面的值是disabled,配置成功后如下:

How to enable SSL/TLS for MySQL server and client(如何设置MySQL服务器和客户端加密传输以及对应Django应用的设置)_第1张图片

step 3:生成客户端加密配置,在同一目录中运行以下命令(因为客户端配置要使用同一认证文件)

openssl req -sha256 -newkey rsa:2048 -days 730 -nodes -keyout client-key.pem > client-req.pem
openssl rsa -in client-key.pem -out client-key.pem
openssl x509 -sha256 -req -in client-req.pem -days 730 -CA ca-cert.pem -CAkey ca-key.pem -set_serial 01 > client-cert.pem

step 4: 配置mysql client ,新建文件~/.my.cnf

[client]
ssl-ca=/home/bi/cert_dir/ca-cert.pem
ssl-cert=/home/bi/cert_dir/client-cert.pem
ssl-key=/home/bi/cert_dir/client-key.pem

注意:如果客户端在另外的主机,需要将服务器端的CA private key and certificate发送到客户端的某个目录,然后在那个目录中执行step 3命令

scp * client@ip:~/cert_dir

对于django应用到这里还是不能友好工作的,需要配置一下认证文件路径指向,如下亲测有效:

DATABASES = {
    ...
    'default': {
        'ENGINE': 'django.db.backends.mysql',
    'OPTIONS': {
        'read_default_file': '/home/lockey/.my.cnf',
    },
        ...
    }
}

你可能感兴趣的:(django,实用工具,数据库)