前言
EMQ X 内置对 TLS/DTLS 的支持,包括支持单双向认证、X.509 证书等多种身份认证和 LB Proxy Protocol V1/2 等。你可以为 EMQ X 支持的所有协议启用 TLS/DTLS,也可以将 EMQ X 提供的 HTTP API 配置为使用 TLS。本文以自签证书的方式介绍如何在 EMQ X 中为 MQTT 启用 TLS。
自签 CA 并签发证书
创建证书
1.准备
$ docker pull centos:centos7
$ docker run -it --name centos7 centos:centos7 /bin/sh
$ yum install openssl
$ yum install vim
$ mkdir /opt/ssl
$ cd /opt/ssl/
$ cp /etc/pki/tls/openssl.cnf ./
$ rm -rf /etc/pki/CA/*.old
## 生成证书索引库数据库文件
$ touch /etc/pki/CA/index.txt
## 指定第一个颁发证书的序列号
$ echo 01 > /etc/pki/CA/serial
$ rm -rf certs;mkdir certs
2.生成 CA 自签名证书
$ openssl genrsa -out certs/root-ca.key 2048
$ openssl req -new -x509 -days 365 -config ./openssl.cnf -key certs/root-ca.key -out certs/root-cacert.pem -subj "/C=CN/ST=hangzhou/O=EMQ/CN=RootCA"
查看证书
$ openssl x509 -in certs/root-cacert.pem -noout -text
...
X509v3 Basic Constraints:
CA:TRUE
...
3.签发客户端证书
$ openssl genrsa -out certs/client.key 2048
$ openssl req -new -days 365 -key certs/client.key -out certs/client-cert.csr -subj "/C=CN/ST=hangzhou/O=EMQ/CN=Client"
$ openssl ca -config ./openssl.cnf -extensions v3_req -days 365 -in certs/client-cert.csr -out certs/client-cert.pem -cert certs/root-cacert.pem -keyfile certs/root-ca.key
查看证书
$ openssl x509 -in certs/client-cert.pem -noout -text
...
X509v3 Basic Constraints:
CA:FALSE
...
4.签发服务端证书
$ openssl genrsa -out certs/server.key 2048
$ openssl req -new -days 365 -key certs/server.key -out certs/server-cert.csr -subj "/C=CN/ST=hangzhou/O=EMQ/CN=Server"
$ openssl ca -config ./openssl.cnf -extensions v3_req -days 365 -in certs/server-cert.csr -out certs/server-cert.pem -cert certs/root-cacert.pem -keyfile certs/root-ca.key
5.验证
$ openssl verify -CAfile certs/root-cacert.pem certs/server-cert.pem
单向认证测试
$ openssl s_server -accept 2009 -key certs/server.key -cert certs/server-cert.pem
$ openssl s_client -connect localhost:2009 -CAfile certs/root-cacert.pem -showcerts
Verify return code: 0 (ok)