物聯網開發筆記 (五) MQTT with SSL

為了確保 MQTT 傳輸資料的安全性,這一篇紀錄使用 openssl 自簽證書的過程

我在 Ubuntu 中使用 openssl,首先先創建資料夾 certs

$ mkdir certs
Create folder
$ openssl genrsa -out certs/ca.key 4096
$ openssl req -new -x509 -days 365 -subj "/C=TW/CN=隨便填" -key certs/ca.key -out certs/ca.crt
建立自簽憑證
openssl genrsa -out certs/server.key 2048
openssl req -new -key certs/server.key -subj "/C=TW/CN={Server IP 或 FQDN}" -out certs/server.csr
openssl x509 -req -CAcreateserial -days 365 -sha256 -CA certs/ca.crt -CAkey certs/ca.key -in certs/server.csr -out certs/server.crt
簽 Server 憑證
注意的是 CA 的 CN 與 Server 的 CN 不能一樣

ca.crtserver.keyserver.crt 移至 /mosquitto/config/certs/ 目錄下。

接著修改 conf

# SSL Port
listener 8883 
protocol mqtt
# Server Private Key
keyfile /mosquitto/config/certs/server.key 
# Server Certificate
certfile /mosquitto/config/certs/server.crt 
# CA Certificate 若不驗證 client 可以不指定 cafile
cafile /mosquitto/config/certs/ca.crt 

# WebSocket SSL Port
listener 8084 
protocol websockets
# Server Private Key
keyfile /mosquitto/config/certs/server.key 
# Server Certificate
certfile /mosquitto/config/certs/server.crt 
# CA Certificate 若不驗證 client 可以不指定 cafile
cafile /mosquitto/config/certs/ca.crt 

測試

有正常收到其他 client 的資料

參考資料

[MQTT] Mosquitto Docker 架設與設定詳細過程
這篇文章記錄了如何使用 Docker 輕鬆架設 MQTT Broker (Mosquitto),並且使用身分驗證、ACL 權限控管,啟動 MQTT/MQTTS/WS/WSS 四個協定。架設伺服器的第一步,就是先將基本設定完善,並確認能夠運行,才能繼續下一步的調教。
Enabling TLS for MQTT: guide with Mosquitto examples | Cedalo
Check out our step-by-step guide on how to configure MQTT TLS for Mosquitto with easy-to-follow examples and ready-to-use snippets of code.
Can’t set up MQTT (Mosquito Docker) + SSL + MQTTNet (C#) + Dapr.io binding
I am trying to set up a local MQTT broker using mosquito image and connect to it with MQTTNet as publisher and subscribe using Dapr MQTT binding. Everything works fine if I am using anonymous mode…