Redis 有个 Protected Mode:没设密码时只接受来自回环地址的连接。它到底在什么条件下生效?加了密码呢?写了 bind 呢?这篇不靠文档转述,直接用本机的回环地址和局域网地址做对照实验。
不带配置文件启动时,Redis 监听所有网卡(bind * -::*),但 protected-mode yes 把非回环来源拦下。启动日志里有一条 WARNING:「Redis does not require authentication. Redis will accept connections from any local client.」——日志说的是「本地」。
经 127.0.0.1 PING → PONG
经 10.83.245.179 PING → (error) DENIED Redis is running in protected mode because protected mode is enabled and no password is set for the default user. In this mode connections are only accepted from the loopback interface.
CONFIG GET bind / protected-mode: ['bind', '* -::*'] ['protected-mode', 'yes']
启动日志里的相关行:
# WARNING: The TCP backlog setting of 511 cannot be enforced because kern.ipc.somaxconn is set to the lower value of 128.
# WARNING: Redis does not require authentication. Redis will accept connections from any local client.
监听地址: *:9160 ; *:9160
运行时执行 CONFIG SET protected-mode no 后,经局域网 PING: PONG本机对自己的局域网地址发起连接,服务端看到的来源是局域网地址,不是回环,所以可以在一台机器上做这个对照。结论:protected-mode 只在「default 用户没有密码」并且来源不是回环时拒绝。
[B bind * · protected-mode yes · 无密码]
经 127.0.0.1 PING → PONG
经 10.83.245.179 PING → (error) DENIED Redis is running in protected mode because protected mode is enabled and no password is set for the default user. In this mode connections are only accepted from the loopback interface.
[C bind * · protected-mode yes · requirepass]
经 127.0.0.1 PING → (error) NOAUTH Authentication required.
经 10.83.245.179 PING → (error) NOAUTH Authentication required.
经 10.83.245.179 先 AUTH 再 PING → PONG
[D bind * · protected-mode no · 无密码]
经 127.0.0.1 PING → PONG
经 10.83.245.179 PING → PONG
[E bind 127.0.0.1 10.83.245.179 · protected-mode yes · 无密码]
经 127.0.0.1 PING → PONG
经 10.83.245.179 PING → (error) DENIED Redis is running in protected mode because protected mode is enabled and no password is set for the default user. In this mode connections are only accepted from the loopback interface.用 ACL 给 default 加密码与 requirepass 等价。
Protected Mode 是最后一道兜底:防的是「忘了配置就暴露」。CONFIG SET protected-mode no 一条命令就能关掉(上面第一节的实验),它也不会保护任何已经在回环上的、来自同机其它进程的连接。真正的保护是密码 / ACL、只 bind 需要的地址、防火墙和 TLS。