Setting Up Two-Factor Authentication for SSH
Adding 2FA to SSH requires both your SSH key/password and a time-based one-time code from an authenticator app.
Step 1 — Install Google Authenticator PAM Module
apt install libpam-google-authenticator -y
Step 2 — Configure for Your User
google-authenticator
Answer the prompts:
- Time-based tokens? Yes
- Scan the QR code with Google Authenticator or Authy on your phone
- Save the emergency scratch codes in a safe place
- Update .google_authenticator? Yes
- Disallow multiple uses? Yes
- Permit tokens up to 30 seconds? Yes
- Enable rate limiting? Yes
Step 3 — Configure PAM
nano /etc/pam.d/sshd
Add at the top:
auth required pam_google_authenticator.so
Step 4 — Configure SSH
nano /etc/ssh/sshd_config
Set or add:
ChallengeResponseAuthentication yes
AuthenticationMethods publickey,keyboard-interactive
Step 5 — Restart SSH
systemctl restart sshd
Important: Test in a second terminal window before closing your current session. You will now be prompted for your SSH key then a verification code.