目录


在Ubuntu 22.04 LTS上实现SSH密码登录的双因素认证(2FA),可以借助开源程序 libpam-google-authenticator,并结合微软的Authenticator应用(该APP可以在手机的应用商店中下载并安装)进行基于时间的一次性密码(TOTP,Time-based One-time Password)认证。以下是指导如何设置:

注意该认证方法无需借助公网环境。

一、安装必要的软件包

  1. 打开终端。
  2. 更新软件包列表:
    sudo apt update
    
    • 1.
  3. 安装 libpam-google-authenticator 包:
    sudo apt install libpam-google-authenticator
    
    • 1.

二、配置每个用户的TOTP

  1. 以需要启用2FA的用户身份登录系统。
    sudo -i -u user_2fa
    
    • 1.
  2. 运行以下命令来生成一个新的密钥和配置文件:
    google-authenticator
    • 1.
  3. 系统会提示你回答一些问题,建议按如下方式回应:
    • Do you want authentication tokens to be time-based (y/n): 输入 y
    • 其他提示可以根据需要选择(y/n)
  4. 生成的二维码会在终端中显示,使用你手机中的微软AuthenticatorAPP扫描此二维码(在已验证ID中点扫描QR码)。
    Your new secret key is:26个字符
    Enter code from app (-1 to skip): 点击Authenticator中的对应项,并输入一次性密码代码。
    Code confirmed
    Your emergency scratch codes are:
    5个8位十进制数(recovery codes)
    其他选项默认选择y即可。
    
    • 1.
    • 2.
    • 3.
    • 4.
    • 5.
    • 6.

三、配置SSH以支持PAM

  1. 编辑SSH配置文件:
    sudo vim /etc/ssh/sshd_config
    
    • 1.
  2. 找到并确保以下行被取消注释并设置为以下内容:
    ChallengeResponseAuthentication yes
    或者
    KbdInteractiveAuthentication yes
    • 1.
    • 2.
    • 3.
  3. 确保 PasswordAuthentication 设置为 yes
    PasswordAuthentication yes
    • 1.

四、配置PAM以使用Google Authenticator

  1. 编辑PAM配置文件:
    sudo vim /etc/pam.d/sshd
    
    • 1.
  2. 在文件的顶部添加以下内容:
    auth required pam_google_authenticator.so
    • 1.

五、重启SSH服务

  1. 保存文件后,退出编辑器(比如:在nano中按 CTRL + X,然后按 Y 确认保存)。
  2. 重启SSH服务以应用更改:
    sudo systemctl restart sshd
    
    • 1.

六、测试设置

  1. 从另一个终端或设备尝试用SSH连接到你的Ubuntu服务器:

    ssh username@your_server_ip
    
    • 1.
  2. 首先,在提示时输入从微软AuthenticatorAPP中获取的TOTP代码(点击Authenticator中的对应项,查看一次性密码代码。),然后输入账户密码。

  3. 登录图示:Ubuntu22.04的ssh密码认证采用2FA_2FA
    上图中Verification code就是TOTP代码,Password是账号本地密码。

  4. 如果使用虚拟终端登录,需要配置身份验证方法为交互式(Keyboard Interactive)

七、注意事项

  • 确保在启用2FA之前,你拥有本地访问,防止因配置错误而无法通过SSH登录。
  • 将TOTP密钥(recovery codes)妥善保管,在TOTP应用失效时可以使用它登录设备(一个code只能用一次),否则将无法再登录设备!