The Begin点点关注,收藏不迷路
|
Redis 作为内存数据库,默认配置并不注重安全性,生产环境必须进行安全加固。以下是 Redis 安全防护的主要方面:
127.0.0.1:6379> CONFIG SET requirepass "YourStrongPassword"
OK
# 编辑 /etc/redis/redis.conf
requirepass YourStrongPassword
import redis
# 创建带认证的连接
r = redis.Redis(
host='localhost',
port=6379,
password='YourStrongPassword',
decode_responses=True
)
# 测试连接
try:
if r.ping():
print("认证成功!")
except redis.exceptions.AuthenticationError:
print("认证失败!")
# redis.conf
bind 127.0.0.1 192.168.1.100
# redis.conf
port 6380
# 只允许特定IP访问
iptables -A INPUT -p tcp --dport 6379 -s 192.168.1.0/24 -j ACCEPT
iptables -A INPUT -p tcp --dport 6379 -j DROP
# redis.conf
rename-command FLUSHDB ""
rename-command FLUSHALL ""
rename-command CONFIG "REDIS-CONFIG"
rename-command SHUTDOWN "REDIS-SHUTDOWN"
命令 | 禁用前 | 禁用后 |
---|---|---|
FLUSHALL | 可以执行 | 命令不存在 |
CONFIG | 可以执行 | 必须使用新名称 |
# redis.conf
tls-port 6379
tls-cert-file /path/to/redis.crt
tls-key-file /path/to/redis.key
# redis.conf
tls-auth-clients yes
tls-ca-cert-file /path/to/ca.crt
为用户 alice 配置权限,使其能够对 password 相关资源(排除 cached:* 范围)执行读取(get)和写入(set)操作。
# 创建用户并设置权限
127.0.0.1:6379> ACL SETUSER alice on >password ~cached:* +get +set
# redis.conf
logfile "/var/log/redis/redis.log"
loglevel notice
# 监控危险命令示例
import redis
r = redis.Redis(decode_responses=True)
pubsub = r.pubsub()
pubsub.psubscribe('__redis__:inspect')
for message in pubsub.listen():
if message['type'] == 'pmessage':
print(f"命令监控: {message['data']}")
认证授权
网络防护
命令安全
数据安全
监控审计
# 确保以下配置
requirepass "StrongPassword123!"
bind 127.0.0.1
protected-mode yes
# 安全的方式执行命令
r = redis.Redis()
# 不安全
user_input = "foo; FLUSHALL"
r.keys(user_input) # 危险!
# 安全
user_input = "foo*"
r.keys(user_input) # 安全
Redis 安全扫描工具
git clone https://github.com/redis-security/redis-security-scanner.git
cd redis-security-scanner
python scanner.py -t 127.0.0.1 -p 6379
Redis 漏洞检查清单
通过本文的配置和最佳实践,可以将 Redis 安全等级提升到生产环境要求,有效防范各类安全威胁。记得每次修改配置后重启 Redis 服务使配置生效。
The End点点关注,收藏不迷路
|