Two-Factor Authentication (2FA) adds an extra layer of security to SSH by requiring a time-based one-time password (TOTP) in addition to your SSH key or password. This guide configures Google Authenticator PAM for SSH 2FA on Ubuntu 24.04 LTS.
Tested and valid on:
- Ubuntu 24.04 LTS
Prerequisites
- Ubuntu 24.04 LTS server
- A user with sudo privileges
- A smartphone with Google Authenticator or Authy installed
Step 1 – Install the Google Authenticator PAM Module
Install the PAM module:
sudo apt update
sudo apt install libpam-google-authenticator -y
Step 2 – Set Up 2FA for Your User
Run the setup for your user account:
google-authenticator
Answer yes to the time-based token question, scan the QR code in your authenticator app, and save the emergency scratch codes.
Step 3 – Configure PAM for SSH
Edit the SSH PAM configuration:
sudo nano /etc/pam.d/sshd
Add at the top:
auth required pam_google_authenticator.so
Step 4 – Configure SSHD
Edit the SSH daemon config:
sudo nano /etc/ssh/sshd_config
Set:
ChallengeResponseAuthentication yes
UsePAM yes
AuthenticationMethods publickey,keyboard-interactive
If using password auth instead of keys:
AuthenticationMethods keyboard-interactive
Step 5 – Restart SSH
Apply the changes:
sudo systemctl restart sshd
Step 6 – Test 2FA Login
Open a new SSH session. After providing your key (or password), you will be prompted for the Verification Code from your authenticator app.
Step 7 – Configure 2FA for Other Users
Each user must run google-authenticator individually to set up their own TOTP secret.
Conclusion
SSH two-factor authentication is now active on Ubuntu 24.04 LTS. Even if an attacker obtains your SSH key, they cannot log in without the current TOTP code from your phone.