第7章 SSL/TLS加密通信
7.1 TLS基础
未加密
明文传输
可被窃听
TLS加密
加密传输
身份验证
数据完整性
7.2 证书类型
X.509证书
CA证书
服务器证书
客户端证书
根证书
中间证书
单域名
通配符
SAN多域名
双向认证
7.3 生成自签名证书
bash
#!/bin/bash
# 生成CA私钥
openssl genrsa -out ca.key 2048
# 生成CA证书
openssl req -new -x509 -days 3650 -key ca.key -out ca.crt \
-subj "/CN=MQTT CA"
# 生成服务器私钥
openssl genrsa -out server.key 2048
# 生成服务器CSR
openssl req -new -key server.key -out server.csr \
-subj "/CN=mosquitto-server"
# CA签名服务器证书
openssl x509 -req -days 365 -in server.csr -CA ca.crt -CAkey ca.key \
-CAcreateserial -out server.crt
# 生成客户端私钥
openssl genrsa -out client.key 2048
# 生成客户端CSR
openssl req -new -key client.key -out client.csr \
-subj "/CN=mqtt-client"
# CA签名客户端证书
openssl x509 -req -days 365 -in client.csr -CA ca.crt -CAkey ca.key \
-CAcreateserial -out client.crt
echo "证书生成完成!"
证书生成流程
开始
生成CA密钥
生成CA证书
生成服务器密钥
生成服务器CSR
CA签名服务器证书
生成客户端密钥
生成客户端CSR
CA签名客户端证书
完成
7.4 Mosquitto TLS配置
单向认证(服务器)
bash
# /etc/mosquitto/mosquitto.conf
# TLS监听器
listener 8883
certfile /etc/mosquitto/certs/server.crt
keyfile /etc/mosquitto/certs/server.key
cafile /etc/mosquitto/certs/ca.crt
# 要求TLS
allow_anonymous false
password_file /etc/mosquitto/passwd
双向认证(客户端证书)
bash
listener 8883
certfile /etc/mosquitto/certs/server.crt
keyfile /etc/mosquitto/certs/server.key
cafile /etc/mosquitto/certs/ca.crt
# 要求客户端证书
require_certificate true
use_identity_as_username true
# 或者使用CA验证
tls_version tlsv1.2
7.5 客户端连接
mosquitto_pub/sub
bash
# 单向认证
mosquitto_sub -h broker.example.com -p 8883 \
--cafile /path/to/ca.crt \
-t "test/#"
# 双向认证
mosquitto_pub -h broker.example.com -p 8883 \
--cafile /path/to/ca.crt \
--cert /path/to/client.crt \
--key /path/to/client.key \
-t "test" -m "hello"
# 跳过证书验证(仅测试)
mosquitto_sub -h localhost -p 8883 \
--insecure \
-t "test/#"
Python客户端
python
import paho.mqtt.client as mqtt
client = mqtt.Client()
client.tls_set(
ca_certs="/path/to/ca.crt",
certfile="/path/to/client.crt",
keyfile="/path/to/client.key",
tls_version=ssl.PROTOCOL_TLSv1_2
)
client.connect("broker.example.com", 8883)
7.6 TLS握手流程
服务器 客户端 服务器 客户端 TLS握手完成 开始加密通信 ClientHello (支持的加密套件) ServerHello (选择的加密套件) + 服务器证书 CertificateRequest (双向认证) 验证服务器证书 客户端证书 (如果请求) ClientKeyExchange (预主密钥) CertificateVerify (签名验证) ChangeCipherSpec Finished ChangeCipherSpec Finished
7.7 安全检查清单
TLS安全检查
证书有效性
加密套件
协议版本
密钥长度
未过期
受信任CA
禁用弱算法
优先ECDHE
TLS 1.2+
禁用SSLv3
RSA 2048+
ECDSA 256+
7.8 本章小结
掌握了Mosquitto的TLS配置,实现了安全的MQTT通信。