MQTT TLS 加密傳輸
Mosquitto原生支持了TLS加密,TLS(傳輸層安全)是SSL(安全套接層)的新名稱,生成證書后再配置一下MQTT代理,本文主要介紹Mqtt如何實現雙向認證和單向認證方法。
單向認證:就是只有服務器提供證書,客戶端不需要證書,雙向認證:服務端和客戶端都提供證書。
1.生成CA
首先我們需要生成證書權威(Certificate Authority,CA)的認證和密鑰,生成過程中Common Name就是hostname,網上很多生成CA證書直接指令OpenSSl方法,沒有對Common Name進行擴展,本文不是主要介紹CA生成方法,這里為方便直接采用github中的一個腳本,可以讓hostname為localhost、本機ip或127.0.0.1,通過鏈接腳本地址運行腳本。
從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是系統名字,也就是服務器端的文件。
其中將三個文件拷貝到/etc/mosquitto目錄:
$ sudo cp ca.crt /etc/mosquitto/ca_certificates/
$ sudo cp host.crt host.key /etc/mosquitto/certs/
2.單向認證
1、配置文件/etc/mosquitto/mosquitto.conf:
# mosquitto.conf
pid_file /var/run/mosquitto.pid
persistence true
persistence_location /var/lib/mosquitto/
log_dest file /var/log/mosquitto/mosquitto.log
port 8883
cafile /etc/mosquitto/ca_certificates/ca.crt
certfile /etc/mosquitto/certs/host.crt
keyfile /etc/mosquitto/certs/host.key
在拷貝證書文件和修改mosiquitto.conf后, 重啟服務:
$ sudo service mosquitto restart
2、單向認證時客戶端不需要生成客戶端證書、鑰匙和請求,僅需要將CA證書ca.crt,ca.key,ca.srl,拷貝到客戶端系統中
客戶端接收mosquitto_sub:
$ mosquitto_sub -p 8883 -t /cnc/knd/# --cafile ca.crt
客戶端發布mosquitto_pub
$ mosquitto_pub -p 8883 -t /cnc/knd/# -m "status"--cafile ca.crt
3.雙向認證
1、若為雙向認證則需根據CA證書生成客戶端證書,生成客戶端證書、鑰匙和請求的方法是在CA證書文件夾下執行OpenSSL
$ openssl genrsa -out client.key 2048
$ openssl req -new -out client.csr -key client.key -subj "/CN=client/O=example.com"
$ openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAserial ./ca.srl -out client.crt -days 3650 -addtrust clientAuth
2、配置文件/etc/mosquitto/mosquitto.conf多一行:
require_certificate true
3、雙向認證時客戶端需要寫入自己的證書信息和密鑰來進行驗證,
客戶端接收mosquitto_sub:
$ mosquitto_sub -p 8883 -t /cnc/knd/# --cafile ca.crt --cert client.crt --key client.key
客戶端發布mosquitto_pub
$ mosquitto_pub -p 8883 -t /cnc/knd/# -m "status"--cafile ca.crt --cert client.crt --key client.key
4. 總結
可以看出雙向認證一個客戶端有一個自己的證書信息,這樣更為安全,但每個客戶端都需要安裝證書也很麻煩,具體采用什么方法,還要考慮實際場合,第一次接觸TLS,如有錯誤,還請指教。