
在网络安全环境中,仅使用密码已不足以保障服务器的安全,设置 SSH 双因素身份验证(2FA) 是增强远程登录安全性的有效手段之一。本文将以 Fedora 41 为例,提供详细、实用的教程,帮助你成功配置 SSH 2FA。
1. 什么是 SSH 双因素身份验证?
SSH(Secure Shell)是最常用的远程登录协议之一,而双因素身份验证 (2FA) 增加了第二道验证机制,进一步提高安全性。除了传统的密码验证外,2FA 要求用户提供额外的认证信息,例如一次性验证码(OTP),以确保即使密码泄露,攻击者也难以访问系统。
在本教程中,我们将使用 Google Authenticator 作为 2FA 的核心工具,配合 SSH 进行安全加固。
2. 准备工作
在开始之前,请确保你已具备以下条件:
- 已安装 Fedora 41
- 具有 root 权限或 sudo 权限的用户
- SSH 服务已启用并正常运行
- 拥有可访问 Google Authenticator(或其他兼容OTP的应用) 的移动设备(如 Google Authenticator、Authy、Microsoft Authenticator 等)
3. 安装 Google Authenticator 模块
首先,使用以下命令安装 Google Authenticator PAM(Pluggable Authentication Module):
sudo dnf install google-authenticator
安装完成后,执行以下命令启动 Google Authenticator 设置:
google-authenticator
系统会引导你完成以下步骤:
3.1 生成密钥和二维码
系统将显示一串密钥、一个二维码,以及相关的应急代码。
- 使用你的手机扫描二维码(通过 Google Authenticator、Authy 等应用)
- 将密钥和应急代码安全地备份,以防手机丢失
3.2 配置选项(推荐设置)
系统会提出一系列问题:
"Do you want authentication tokens to be time-based (y/n)?" → 输入 `y`
"Do you want me to update your "/home/username/.google_authenticator" file?" → 输入 `y`
"Do you want to disallow multiple uses of the same token? (y/n)" → 输入 `y`
"Do you want to increase the time window?" → 输入 `n`(除非需要更长的时间窗口)
"Do you want to enable rate-limiting?" → 输入 `y`(推荐,防止暴力破解)
此时,`~/.google_authenticator` 文件已生成并配置完成。
4. 配置 PAM 以启用 2FA
下一步是配置 PAM 以便 SSH 登录时使用 Google Authenticator 模块:
1). 打开 PAM 配置文件:
sudo nano /etc/pam.d/sshd
2). 在文件顶部添加以下行:
auth required pam_google_authenticator.so
3). 保存并退出 (`Ctrl + X`, 输入 `Y`, 回车)
5. 配置 SSH 服务以支持 2FA
编辑 SSH 配置文件:
sudo nano /etc/ssh/sshd_config
找到并修改以下参数:
ChallengeResponseAuthentication yes
UsePAM yes
AuthenticationMethods publickey,password publickey,keyboard-interactive
⚠️ 重要提醒
- `ChallengeResponseAuthentication` 必须设为 `yes`,否则 SSH 将忽略 PAM 的 2FA 设置。
- `AuthenticationMethods` 这一行表示你既可以使用 公钥 + 密码,也可以使用 公钥 + 2FA。
6. 重新启动 SSH 服务
完成配置后,重启 SSH 服务以应用更改:
sudo systemctl restart sshd
7. 测试 SSH 双因素身份验证
现在测试 SSH 登录,执行以下命令:
ssh username@your_server_ip
- 首先输入密码
- 随后系统会要求你输入 Google Authenticator 生成的动态验证码(OTP)
- 如果输入正确,即可成功登录
8. 故障排查
如果遇到问题,请检查以下方面:
- 使用 `sudo systemctl status sshd` 检查 SSH 服务状态
- 查看 `/var/log/secure` 以获取 SSH 登录日志
- 确保 `pam_google_authenticator.so` 已成功加载
9. 提升安全性的进阶技巧
禁用密码登录,强制使用公钥 + 2FA
在 `/etc/ssh/sshd_config` 中设置:
PasswordAuthentication no
配置 Fail2Ban 防止暴力破解攻击
安装并配置 Fail2Ban,以阻止频繁失败的登录尝试:
sudo dnf install fail2ban
sudo systemctl enable --now fail2ban
使用防火墙限制 SSH 访问
限制 SSH 服务仅对特定 IP 地址或子网开放:
sudo firewall-cmd --add-service=ssh --permanent
sudo firewall-cmd --reload
完成上述配置后,你的 Fedora 41 系统已启用 SSH 双因素身份验证,大幅提高了远程访问的安全性。无论是个人服务器还是企业环境,这种额外的安全层都能有效抵御暴力破解、凭证泄露等风险。











