继前一篇:ubuntu搭建mqtt服务器及验证 后,本篇介绍如何搭建mqtts服务器。
mqtts即mqtt + tls,在原有mqtt基础上添加证书加密能力,使传播消息不被破解。好在mosquitto已经支持TLS加密和单双向认证,本文介绍其配置方法。
1. 生成证书
如果有证书可跳过本步骤,可以用openssl生成证书。采用github上OweTracks项目下载并运行generate-CA.sh脚本。该脚本创建CA文件,生成服务器证书,并使用CA来签名证书。
运行脚本
$ mkdir myca
$ cd myca
$ bash ./generate-CA.sh
generate-CA.sh会产生6个文件:ca.crt,ca.key,ca.srl,host.crt,host.csr和host.key。分别为: 证书(.CRT),钥匙(.KEY),请求(.csr文件),并在签名过程中的一系列记录文件(.slr),注意host是系统名字,也就是服务器端的文件。
将证书文件拷贝到mosquitto配置目录/etc/mosquitto下:
$ sudo cp ca.crt /etc/mosquitto/ca_certificates/
$ sudo cp host.crt host.key /etc/mosquitto/certs/
2. mosquitto配置
mosquitto支持多端口监听,为了验证配置的正确性,我们在5678端口上配置单向验证。
/etc/mosquitto/mosquitto.conf配置文件内容:
# Place your local configuration in /etc/mosquitto/conf.d/
#
# A full description of the configuration file is at
# /usr/share/doc/mosquitto/examples/mosquitto.conf.example
pid_file /var/run/mosquitto.pid
persistence true
persistence_location /var/lib/mosquitto/
log_dest file /var/log/mosquitto/mosquitto.log
include_dir /etc/mosquitto/conf.d
我们只需将不同端口的配置文件放在conf.d目录下即可。
单向认证配置如下:
listener 5678
cafile /etc/mosquitto/ca_certificates/ca.crt
certfile /etc/mosquitto/certs/server.crt
keyfile /etc/mosquitto/certs/server.key
使用root用户启动mosquitto程序:mosquitto -c /etc/mosquitto/mosquitto.conf
3. 验证
在本机使用mosquitto_pub,mosquitto_sub命令验证mqtts通信
在命令行中通过cafile指定证书文件路径,连接mosquitto服务器。
sub: mosquitto_sub -p 5678 -t topic --cafile /etc/mosquitto/ca_certificates/ca.crt -v
pub: mosquitto_pub -p 5678 -t topic --cafile /etc/mosquitto/ca_certificates/ca.crt -m hello
4. emqx服务器
-
搭建emqx服务器
在emqx官网https://www.emqx.io/zh/downloads下载页面选择下载安装包,我选择ubuntu 18.04版本。mkdir emqx cd emqx wget https://www.emqx.com/zh/downloads/broker/5.0.0/emqx-5.0.0-otp24.2.1-1-ubuntu18.04-amd64.tar.gz tar -zxvf emqx-5.0.0-otp24.2.1-1-ubuntu18.04-amd64.tar.gz ./bin/emqx start查看emqx/etc/emqx.conf配置发现emqx提供了mqtt, mqtts, ws, wss四种能力。另外dashboard中显示它提供了一个web页面方便界面操作管理。
在安装机器上打开浏览器,输入: 127.0.0.1:18083,用户名密码为admin/public就可以登录该管理页面。 -
emqx mqtts验证
emqx默认单向认证,其ca证书文件为:etc/certs/cacert.pem。我们用mosquitto_sub连接,却报错:mosquitto_sub -v -p 8883 -t topic --cafile ./etc/certs/cacert.pem Error: A TLS error occurred.查看emqx的日志,并不是报证书不对。所以这是一个坑点。需要加上
--insecure选项,该选项表示不校验证书主机名与emqx服务主机名是否一致。
将mosquitto服务器验证时生成的证书文件等拷贝到etc/certs下,并在管理界面重新配置证书路径,重启emqx,则在执行mosquitto_sub或mosquitto_pub正常。
本文详细介绍了如何在Ubuntu系统上搭建带TLS加密的MQTTs服务器,包括证书生成、mosquitto配置、验证过程以及EMQX服务器的设置。在配置mosquitto时,重点讲解了单向认证的配置步骤,并在验证阶段提到了mosquitto_sub和mosquitto_pub的使用。此外,还讨论了在EMQX服务器上配置证书以实现正常通信的方法。
1698

被折叠的 条评论
为什么被折叠?



