Redis 启用 TLS 加密传输配置
一、Redis TLS 加密概述
Redis 从 6.0 版本开始原生支持 TLS 加密传输,可以保护客户端与服务器之间的通信安全,防止数据被窃听或篡改。
二、准备工作
确认 Redis 版本:
redis-server --version
确保版本 ≥ 6.0
安装依赖:
sudo apt-get install openssl
三、生成 TLS 证书
1. 创建证书目录
mkdir -p /etc/redis/certs
cd /etc/redis/certs
2. 生成 CA 私钥和证书
openssl genrsa -out ca.key 4096
openssl req -x509 -new -nodes -key ca.key -sha256 -days 3650 -out ca.crt
- 生成 Redis 服务器证书
# 生成私钥
openssl genrsa -out redis.key 2048# 创建证书签名请求 (CSR)
openssl req -new -key redis.key -out redis.csr# 使用 CA 签署证书
openssl x509 -req -in redis.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out redis.crt -days 365 -sha256# 合并证书和私钥
cat redis.key redis.crt > redis.pem
4. 设置权限
chown redis:redis /etc/redis/certs/*
chmod 600 /etc/redis/certs/*
四、配置 Redis 服务器 TLS
编辑 /etc/redis/redis.conf:
# 启用 TLS
tls-port 6379
port 0 # 禁用非 TLS 端口# 证书配置
tls-cert-file /etc/redis/certs/redis.crt
tls-key-file /etc/redis/certs/redis.key
tls-ca-cert-file /etc/redis/certs/ca.crt# 安全设置
tls-auth-clients yes # 要求客户端使用证书
tls-protocols "TLSv1.2 TLSv1.3"
tls-ciphers DEFAULT:!MEDIUM
tls-ciphersuites TLS_CHACHA20_POLY1305_SHA256
tls-prefer-server-ciphers yes
五、重启 Redis 服务
sudo systemctl restart redis-server
六、客户端连接配置
###1. Redis CLI 连接
redis-cli --tls \--cert /etc/redis/certs/redis.crt \--key /etc/redis/certs/redis.key \--cacert /etc/redis/certs/ca.crt
2. 编程语言客户端示例
PHP (Predis)
$client = new Predis\Client(['scheme' => 'tls','host' => 'your.redis.host','port' => 6379,'ssl' => ['cafile' => '/path/to/ca.crt','verify_peer' => true]
]);
Python (redis-py)
import redisr = redis.Redis(host='your.redis.host',port=6379,ssl=True,ssl_ca_certs='/path/to/ca.crt',ssl_cert_reqs='required'
)
七、高级配置选项
双向认证:
tls-auth-clients yes
仅允许特定密码套件:
tls-ciphers "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384"
会话缓存:
tls-session-caching yes
tls-session-cache-size 1000000
tls-session-cache-timeout 300
八、测试与验证
测试连接:
openssl s_client -connect localhost:6379 -cert /etc/redis/certs/redis.crt -key /etc/redis/certs/redis.key -CAfile /etc/redis/certs/ca.crt
查看 TLS 信息:
redis-cli --tls -a yourpassword --no-auth-warning --tls-ca-cert-file /etc/redis/certs/ca.crt INFO SECURITY
九、常见问题解决
证书错误:
- 确保证书路径正确
- 检查证书权限 (redis 用户可读)
- 验证证书有效期
连接失败:
sudo tail -f /var/log/redis/redis-server.log
性能调优:
- 对于高并发场景,考虑启用会话缓存
- 监控 TLS 握手性能
十、安全最佳实践
- 定期轮换证书 (建议每年一次)
- 禁用旧版 TLS 协议 (如 TLS 1.0/1.1)
- 监控证书过期时间
- 考虑使用证书管理工具 (如 certbot)
- 在生产环境使用受信任的 CA 签发证书