Overview
Two-factor authentication (2FA) adds a second layer of security to SSH by requiring a time-based one-time password (TOTP) in addition to your SSH key or password.
Install Google Authenticator PAM
sudo apt install -y libpam-google-authenticatorConfigure Per User
As the user who will use 2FA:
google-authenticatorAnswer the prompts:
- Time-based tokens? Yes
- Update the .google_authenticator file? Yes
- Disallow multiple uses? Yes
- Rate limiting? Yes
Scan the QR code with your authenticator app (Google Authenticator, Authy, or any TOTP app).
Configure PAM
Edit /etc/pam.d/sshd:
# Add at the end
auth required pam_google_authenticator.soConfigure SSHD
Edit /etc/ssh/sshd_config:
ChallengeResponseAuthentication yes
AuthenticationMethods publickey,keyboard-interactiveThis requires both an SSH key AND a TOTP code.
Restart SSH
sudo systemctl restart sshdTesting
ssh -o PreferredAuthentications=publickey,keyboard-interactive user@server
# You will be prompted for your verification code after key authBackup Codes
During setup, you received emergency scratch codes. Store these securely — they can be used if you lose your authenticator device. Each backup code can only be used once.
Important Notes
- Keep an active SSH session open while configuring — if something goes wrong, you can fix it
- Test from a new terminal before closing your current session
- Store backup codes in a password manager