Adding 2FA provides an additional security layer. Even if someone steals your private key, they can’t access the server without the second factor.
Install Google Authenticator
# Ubuntu/Debiansudo apt install libpam-google-authenticator
# RHEL/CentOSsudo yum install google-authenticatorConfigure 2FA for Your User
google-authenticatorAnswer the prompts:
- Do you want time-based tokens? Yes
- Update ~/.google_authenticator? Yes
- Disallow multiple uses? Yes
- Increase time window? No (unless you have time sync issues)
- Enable rate-limiting? Yes
Scan the QR code with your authenticator app (Google Authenticator, Authy, etc.).
Configure PAM
Edit PAM configuration:
sudo nano /etc/pam.d/sshdAdd at the top:
auth required pam_google_authenticator.so nullokThe nullok option allows users without 2FA configured to still login. Remove it once all users have 2FA set up.
Enable 2FA in SSH
Edit /etc/ssh/sshd_config:
ChallengeResponseAuthentication yesAuthenticationMethods publickey,keyboard-interactiveRestart SSH:
sudo systemctl restart sshdNow connections require both your SSH key AND the 2FA code.
Next Steps
For advanced enterprise scenarios, explore the Host-Based Authentication guide to configure automated server-to-server trust relationships.