Two-Factor Authentication (2FA) adds a second layer of protection to SSH: even if your password or key were compromised, an attacker still couldn't log in without a time-based code from your phone. This guide uses Google Authenticator PAM module, which works with any TOTP app (Google Authenticator, Authy, 1Password, etc.).
Prerequisites
- Ubuntu 22.04/24.04 or Debian 11/12 VPS
- Root or sudo access
- An authenticator app on your phone
Step 1 — Install the PAM Module
sudo apt update
sudo apt install libpam-google-authenticator -y
Step 2 — Generate a Token for Your User
google-authenticator
Answer the setup prompts:
- Generate time-based tokens: Yes
- Update the configuration file: Yes
- Disallow multiple uses of the same token: Yes
- Increase brute-force protection window: Yes
- Enable rate limiting: Yes
Scan the displayed QR code with your authenticator app, and save the printed emergency recovery codes somewhere safe.
Step 3 — Configure PAM
sudo nano /etc/pam.d/sshd
Add this line at the end:
auth required pam_google_authenticator.so
Step 4 — Configure SSH
sudo nano /etc/ssh/sshd_config
Make sure these are set:
KbdInteractiveAuthentication yes
UsePAM yes
If you use SSH key + 2FA together (recommended), also add:
AuthenticationMethods publickey,keyboard-interactive
Step 5 — Restart SSH
sudo systemctl restart ssh
Step 6 — Test in a New Session
Without closing your current session, open a new terminal and connect. You should be prompted for your SSH key (if configured) and then a verification code.
Common Errors
Locked out after enabling 2FA — use your VPS provider's console to log in and remove the pam_google_authenticator.so line from /etc/pam.d/sshd.
Codes rejected even though correct — your server's clock may be out of sync. Check with timedatectl and enable NTP.
Best Practices
- Always keep the emergency recovery codes in a secure, offline location
- Combine 2FA with SSH keys (
AuthenticationMethods publickey,keyboard-interactive) rather than passwords + 2FA - Test 2FA on a new session before closing your existing one
FAQ
Does this work with any authenticator app?
Yes, any TOTP-compatible app works: Google Authenticator, Microsoft Authenticator, Authy, 1Password, etc.
What if I lose my phone?
Use one of the emergency recovery codes generated during setup, or your provider's console access.
Continue Reading
- SSH Hardening: Change the Port, Disable Root Login & Use SSH Keys
- How to Install and Configure Fail2Ban
- VPS Security Checklist for Beginners
Browse more articles in Server Security & Hardening.
