Mosquitto配置SSL

生成证书

安装openssl包后,依次执行下面的命令:

openssl genrsa -des3 -out ca.key 2048
openssl req -new -x509 -days 3600 -key ca.key -out ca.crt
openssl genrsa -out server.key 2048
openssl req -new -out server.csr -key server.key
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 3000

注意Common Name必须与服务器的IP或域名完全相同。

配置

注意tls_version版本最好设为1.2,因为mosquitto命令行客户端默认用的的这个版本。

....
listener 8333
cafile /opt/apps/mqtt-cert/ca.crt
keyfile /opt/apps/mqtt-cert/server.key
certfile /opt/apps/mqtt-cert/server.crt
tls_version tlsv1.2
....

Mosquitto支持多协议、多端口,如果不想使用非加密协议,删除相应的端口配置内容即可。

测试

测试时可以用--insecure跳过证书域名的检查。

mosquitto_sub --cafile /opt/apps/mqtt-cert/ca.crt  -h localhost --insecure -u fakeusername -P fakepassword -p 7333 -t test/me
mosquitto_pub --cafile /opt/apps/mqtt-cert/ca.crt  -h localhost --insecure -u fakeusername -P fakepassword -p 7333 -t test/me -m 'hello world'

Refs

mosquitto-tls

一个完整的配置文件

完整的Mosquitto配置文件,供参考:

# mosquitto运行的用户
user jane
pid_file /opt/apps/data/mosquitto/mosquitto.pid
# 密码文件
password_file /opt/apps/data/mosquitto/passwd

# 持久化设置
persistence true
persistence_location /opt/apps/data/mosquitto/data
# 日志目录
log_dest file /opt/apps/data/mosquitto/log/mos.log

# SSL配置
listener 7333
cafile /opt/apps/mqtt-cert/ca.crt
keyfile /opt/apps/mqtt-cert/server.key
certfile /opt/apps/mqtt-cert/server.crt
tls_version tlsv1.2

# 禁用匿名访问
allow_anonymous  false

客户端使用

使用个人SSL证书后,客户端需要导入证书才能使用。你可以在程序里导入证书。如果有root权限,最方便的办法是将生成的CA证书导入服务器,具体办法可以参考为JDK导入CA根证书

Comment