MQTT通讯 安全性(linux下配置)

1.MQTT通讯 安全性说明

  • MQTT 协议没有对安全性设置强制标准,只是在第五章提出了建议,提供合适的安全功能是实现者的责任。
  • 默认情况下,mosquitto 不需要任何验证,用户可以匿名连接。如果设置了 allow_anonymous false ,客户端必须提供正确的用户名和密码进行验证,连接时应该将用户名和密码加密传输,否则有被拦截的危险。
  • 此外,mosquitto 还提供基于 SSL/TLS 证书的安全验证,使用 OpenSSL 作为 SSL/TLS 的实现。

2.SSL/TLS 

我们可以通过这个脚本https://github.com/owntracks/tools/raw/master/TLS/generate-CA.sh 自建 CA 并颁发证书:

  • $ wget https://github.com/owntracks/tools/raw/master/TLS/generate-CA.sh .
  • $ ./generate-CA.sh

生成的文件:

  • ca.crt ,CA 根证书
  • localhost.crt ,mosquitto 服务器上的证书
  • localhost.key ,mosquitto 服务器上的密钥

将这三个文件复制到 /etc/mosquitto/certificates/ 目录下。然后修改配置文件,开启 SSL/TLS :

  • port 8883
  • cafile /etc/mosquitto/certificates/ca.crt
  • certfile /etc/mosquitto/certificates/localhost.crt
  • keyfile /etc/mosquitto/certificates/localhost.key
  • require_certificate true
  •  

启动 mosquitto :

  • $ mosquitto -c /etc/mosquitto/mosquitto.conf -v
  • 1495335112: mosquitto version 1.4.11 (build date 2017-05-20 17:44:03+0800) starting
  • 1495335112: Config loaded from /etc/mosquitto/mosquitto.conf.
  • 1495335112: Opening ipv4 listen socket on port 8883.
  • 1495335112: Opening ipv6 listen socket on port 8883.
  •  

再用根证书为客户端生成密钥和证书:

  • $ openssl genrsa -out client.key 2048
  • $ openssl req -new -out client.csr -key ./client.key
  • $ openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAserial ./ca.srl -out client.crt -days 3650 -addtrust clientAuth
  •  

将根证书 ca.crt 、客户端密钥 client.key 、证书 client.crt 发送给客户端,本地测试的话,直接连接 localhost :

  • $ mosquitto_sub -h localhost -p 8883 -t \$SYS/broker/bytes/\# -v --cafile ca.crt --cert client.crt --key client.key
  • $SYS/broker/bytes/received 0
  • $SYS/broker/bytes/sent 0
  •  

如果设置了 require_certificate false ,就是 SSL 单向认证,客户端只需提供 cafile,也无需设置 --cert 和 --key 。如果设置了 allow_anonymous false ,还要提供用户名和密码,否则会客户端会报错:

  • $ mosquitto_sub -h localhost -p 8883 -t \$SYS/broker/bytes/\# -v --cafile ca.crt --cert client.crt --key client.key
  • Connection Refused: not authorised.

3.WebSockets with SSL/TLS

mosquitto 编译时默认是不支持 WebSockets 的,需要在 config.mk 中将 WITH_LIBWEBSOCDETS:=no 改为 yes 。在配置文件中追加 WebSockets 的选项,并加上用户名和密码:

  • listener 8884
  • protocol websockets
  • password_file /etc/mosquitto/mosquitto.password

然后重启 mosquitto 。可以在 http://www.hivemq.com/demos/websocket-client/ 页面测试,这是一个 Websockets Client 。输入 mosquitto 服务器的 IP 、端口、用户名和密码,即可连接,然后添加订阅话题:

希望对你有帮助。

猜你喜欢

转载自blog.csdn.net/qq_41204464/article/details/94045618