1、/etc/mosquitto/mosquitto.conf文件配置
persistence true
persistence_location /var/lib/mosquitto/
log_dest file /var/log/mosquitto/mosquitto.log
include_dir /etc/mosquitto/conf.d
listener 1883
listener 8883 0.0.0.0
password_file /etc/mosquitto/pwfile
certfile /home/server.crt
keyfile /home/server_private.key
cafile /home/ca.crt
require_certificate true
allow_anonymous false
2、生成证书,注意server的CN需要设置为服务端的IP地址
#!/usr/bin/env bash
# CA key
openssl genrsa -out ca.key 2048
# CA csr
openssl req -new -subj "/C=CN/ST=GD/L=SZ/O=LY/OU=NSP/CN=ca" -key ca.key -out ca.csr
# CA crt
openssl x509 -req -in ca.csr -out ca.crt -signkey ca.key -days 3650
# server key
openssl genrsa -out server_private.key 2048
# server.csr
openssl req -new -subj "/C=CN/ST=GD/L=SZ/O=LY/OU=NSP/CN=192.168.56.101" -key server_private.key -out server.csr
# server.crt
openssl x509 -req -in server.csr -out server.crt -CA ca.crt -CAkey ca.key \
-CAcreateserial -days 3650
# server.crt verify
openssl verify -CAfile ca.crt server.crt
# client key
openssl genrsa -out client_private.key 2048
# client.csr
openssl req -new -subj "/C=CN/ST=GD/L=SZ/O=LY/OU=NSP/CN=client" -key client_private.key -out client.csr
# client.crt
openssl x509 -req -in client.csr -out client.crt -CA ca.crt -CAkey ca.key \
-CAcreateserial -days 3650
# client.crt verify
openssl verify -CAfile ca.crt client.crt
3、执行测试命令
mosquitto_pub -d -h 192.168.56.101 -p 8883 -t "topic/test" -u admin -P admin --cafile ca.crt --cert client.crt --key client_private.key -m "are you ok" -i client
4、调试问题,Ubuntu安装的mosquitto 版本为 2.0.15,使用openssl自签服务端和客户端证书时候由于服务端证书Common Name没有设置为服务器的ip地址,出现以下服务端证书验证失败的问题。
Client client sending CONNECT
Error: host name verification failed.
OpenSSL Error[0]: error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed
Error: Protocol error