服务器配置2FA

Google Authenticator 是一款基于软件的两步验证工具,它使用基于时间的一次性密码算法(TOTP)和基于 HMAC 的一次性密码算法(HOTP)为用户提供验证。

要在 Linux 上使用这项服务,你需要安装名为libpam-google-authenticator或google-authenticator的软件包。这个包提供了一个模块,能将 Google Authenticator 集成到 Linux 的 PAM 系统中。

安装

  • 手机端安装Microsoft Authenticator、Google Authenticator等2FA App
  • 服务器端安装google-authenticator
# 安装
dnf install epel-release
dnf install google-authenticator

google-authenticator
  • 执行命令后会提示Do you want authentication tokens to be time-based
  • 回答y启用基于时间的一次性密码
  • 会展示二维码,如网络原因不显示则复制Your new secret key is: 后的密钥
  • 手机端打开安装好的 2FA 应用,点击「+」加号添加帐户
  • 保存完成后输入6位挑战码,完成绑定

配置

  • selinux启用情况下,需要临时将selinux停用setenforce 0
  • 修改/etc/ssh/sshd_config,将ChallengeResponseAuthentication设置为启用
# 需要仅启用2FA验证停用文本密码,则需要将KbdInteractiveAuthentication停掉
# KbdInteractiveAuthentication yes # 启用后,SSH 服务器会在输入密码后要求输入手机上 2FA 应用生成的验证码
ChallengeResponseAuthentication yes # 启用后,SSH 服务器会使用「挑战-响应」认证,即提示输入验证码
UsePam yes
  • 完成修改后重启sshd,systemctl restart sshd
  • 修改/etc/pam/sshd
#auth       substack     password-auth # 如果需要仅启用2FA验证停用文本密码,则注释密码认证的pam
auth       required     pam_google_authenticator.so # 引入2fa pam
  • 保持原有ssh客户端会话,新开ssh客户端登录测试
  • 检查selinux审计记录,并保存规则

将google_authenticator的审计生成规则

grep -i google_authenticator /var/log/audit/audit.log | audit2allow -M mypol

如缺少selinux工具则安装

dnf install -y policycoreutils-python-utils

保存规则

semodule -i mypol.pp

重新启用selinux

setenforce 1


- 如果登录失败,检查`/var/log/secure`和` /var/log/audit/audit.log`,可重复执行selinux规则生成
- 检查`~/.google_authenticator`权限是否为500