Redis 設計為高速記憶體資料庫,預設無密碼、綁定 0.0.0.0、無加密傳輸,直接暴露在公網極度危險。必須採取多層防護:
編輯 redis.conf:
# 僅允許本機存取(預設)
bind 127.0.0.1
# 或允許特定內網網段
bind 127.0.0.1 192.168.1.100 10.0.0.50
# 啟用後需指定設定檔啟動
redis-server /etc/redis/redis.conf
缺點:無法支援多台應用伺服器共享同一 Redis,擴充性差。
# 設定密碼(建議 32 字元以上高熵值字串)
requirepass your_very_strong_random_password_here_2024
產生強密碼:
openssl rand -base64 32
systemctl restart redis
# 或
redis-cli shutdown
redis-server /etc/redis/redis.conf
# 互動模式
redis-cli -h 192.168.1.100 -a 'your_password'
# 或連線後驗證
redis-cli -h 192.168.1.100
192.168.1.100:6379> AUTH your_password
OK
# 指令列一次性執行
redis-cli -h 192.168.1.100 -a 'your_password' KEYS '*'
# 較安全寫法(避免密碼留在歷史紀錄)
redis-cli -h 192.168.1.100 --askpass KEYS '*'
編輯 redis.conf,將高風險指令改名或禁用:
# 完全禁用
rename-command FLUSHDB ""
rename-command FLUSHALL ""
rename-command KEYS ""
rename-command CONFIG ""
rename-command SHUTDOWN ""
rename-command DEBUG ""
rename-command EVAL "" # Lua 腳本可能注入
# 或改名為難以猜測的字串
rename-command CONFIG "CONFIG_b8f3a2e9"
rename-command KEYS "KEYS_7d2f1c4a"
注意:改名後所有客戶端程式碼、監控工具、備份腳本都必須同步更新。
<?php
$redis = new Redis();
$redis->connect('192.168.1.100', 6379);
$redis->auth('your_very_strong_random_password_here_2024');
// 設定連線選項
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_IGBINARY); // 高效序列化
$redis->setOption(Redis::OPT_PREFIX, 'myapp:'); // 金鑰前綴避免衝突
// 基本操作
$redis->set('user:1:name', 'Alice');
$name = $redis->get('user:1:name');
// 管線批次操作(減少 RTT)
$pipe = $redis->multi(Redis::PIPELINE);
for ($i = 0; $i < 1000; $i++) {
$pipe->set("key:$i", "value:$i");
}
$pipe->exec();
?>
<?php
require 'vendor/autoload.php';
$client = new Predis\Client([
'scheme' => 'tcp',
'host' => '192.168.1.100',
'port' => 6379,
'password' => 'your_very_strong_random_password_here_2024',
'database' => 0,
'prefix' => 'myapp:',
'read_write_timeout' => 2,
'timeout' => 1,
]);
$client->set('foo', 'bar');
$value = $client->get('foo');
?>
requirepass,Replica 設定 masterauth 相同密碼。requirepass 相同,客戶端連線時提供密碼即可。sentinel auth-pass <master-name> <password>。Redis 單秒可處理 10 萬+ 指令,極易遭密碼噴灌攻擊:
openssl rand -base64 32 產生。protected-mode yes(預設開啟),無密碼且非本機連線會被拒絕。fail2ban 監控 Redis 日誌封鎖異常 IP。| 錯誤 | 原因 | 解決 |
|---|---|---|
| NOAUTH Authentication required | 未提供密碼或密碼錯誤 | 檢查客戶端 auth 參數、redis.conf requirepass 設定 |
| ERR operation not permitted | 指令被 rename-command 禁用 | 確認指令是否被改名,或暫時開放該指令 |
| Connection refused | bind 設定錯誤/防火牆阻擋/Redis 未啟動 | 檢查 bind、netstat -ltnp、firewall-cmd/iptables |