为 SSH 增加 TOTP 二次验证,是成本最低的服务器安全加固手段之一。即使 SSH 私钥完全泄露,攻击者也无法在 30 秒窗口内暴力破解 6 位动态验证码。本文基于 PAM 模块,给出 Ubuntu/Debian 和 RHEL/CentOS 的完整部署步骤。


一、威胁模型

SSH 密钥登录比密码登录安全——但它仍是单因素认证。私钥泄露场景:

  • 开发机被入侵 → ~/.ssh/id_rsa 被窃取
  • 笔记本丢失 → 私钥随设备落入他人之手
  • 私钥未设密码保护 → 拿到文件即可使用

增加 TOTP 后:SSH 私钥验证 → 通过 → 输入 6 位 TOTP 验证码 → 通过 → 登录成功。攻击者即使拿到私钥,没有当前 30 秒窗口的 TOTP 验证码,仍无法登录。


二、技术架构

SSH 登录请求
    ↓
sshd (ChallengeResponseAuthentication + AuthenticationMethods)
    ↓
PAM stack (/etc/pam.d/sshd)
    ↓
pam_google_authenticator.so
    ↓
读取 ~/.google_authenticator(用户级密钥配置)
    ↓
验证通过 → 允许登录 / 失败 → 拒绝

pam_google_authenticator.so 实现 RFC 6238 TOTP 标准,纯离线工作,不依赖任何外部服务。


三、部署步骤

3.1 安装 PAM 模块

# Ubuntu / Debian
sudo apt update
sudo apt install libpam-google-authenticator

# RHEL / CentOS / Rocky Linux
sudo dnf install epel-release
sudo dnf install google-authenticator

3.2 生成 TOTP 密钥

google-authenticator

关键选项:Time-based tokens → y;Disallow multiple uses → y(防重放攻击);其余保持默认。

执行后终端显示二维码和 5 个紧急恢复码,立即离线保存恢复码。扫码时可使用任意 TOTP 验证器,如 Google Authenticator、Microsoft Authenticator,或微信小程序「二次验证码Free2FA」(支持自动加密云备份,换手机后同一微信登录即可恢复全部密钥)。

3.3 配置 PAM

/etc/pam.d/sshd 末尾添加:

auth required pam_google_authenticator.so

3.4 配置 sshd

/etc/ssh/sshd_config

ChallengeResponseAuthentication yes
AuthenticationMethods publickey,keyboard-interactive:pam
UsePAM yes

publickey,keyboard-interactive:pam 意为先验证公钥,再触发 PAM 交互要求 TOTP。

sudo systemctl restart sshd

⚠️ 不要关闭当前 SSH 会话,另开终端测试确认无误后再关原会话。


四、运维注意事项

时间同步

TOTP 依赖时间,偏差超 30 秒会导致验证失败:

sudo systemctl enable --now systemd-timesyncd  # Debian 系
sudo systemctl enable --now chronyd            # RHEL 系

入职与离职

入职:sudo su - newuser && google-authenticator,新员工扫码并保存恢复码。

离职:sudo usermod -L username && sudo rm /home/username/.google_authenticator

紧急恢复

每个用户初始化时生成 5 个紧急恢复码,丢失 TOTP 设备时可用恢复码登录后重新配置。


五、替代方案

方案 适用场景
pam_oath 更轻量的 OATH TOTP/HOTP
pam_duo 商业方案,推送通知体验更好
自建 TOTP 网关 大规模集群统一校验层前置

六、总结

投入约 10 分钟配置。效果:即使 SSH 私钥完全泄露,攻击者仍无法登录。

Logo

openEuler 是由开放原子开源基金会孵化的全场景开源操作系统项目,面向数字基础设施四大核心场景(服务器、云计算、边缘计算、嵌入式),全面支持 ARM、x86、RISC-V、loongArch、PowerPC、SW-64 等多样性计算架构

更多推荐