ssh配置双因子验证

0. 准备环境

实验环境

  • OS: Debian GNU/linux 12
  • SSH: openSSH

安装Google Authenticator

1
# apt install libpam-google-authenticator

1. 绑定动态验证码

在移动设备上安装 Authenticator。然后,在需要使用动态验证码的账户上执行:

1
$ google-authenticator

使用刚刚安装的程序扫描输出的二维码,即可绑定到设备上。

执行过程中会要求配置一些东西,按需求配置即可。

2. 修改 pam 配置

1
# vim /etc/pam.d/sshd

注释掉@include common-auth

1
# @include common-auth

如果不注释这一行,当配置公钥登录时,会跳过 2FA 步骤。

account required pam_nologin.so后面增加一行

1
2
  account required pam_nologin.so
+ auth required pam_google_authenticator.so nullok

在配置完这一步后,需要继续完成后续配置,否则断开链接后无法继续使用 ssh 登陆。
nullok 用于在没有配置 2FA 的情况下能够使用传统方法登录

3. 修改 sshd 配置

1
# vim /etc/ssh/sshd_config

搜索KdbInteractiveAuthentication,将后面的no修改为yes

4. 应用修改

1
# systemctl reload sshd.service

5. 验证

开启一个新的 ssh 连接,测试是否需要两步验证才能登陆

1
2
3
# ssh <username>@<host>
(<username>@<host>) Password:
(<username>@<host>) VerifacationCode:

出现类似VerifacationCode关键字说明配置成功

6. 待续

  • 允许特定用户跳过2FA步骤