Enable TOTP 2FA for SSH Access
Configure TOTP two-factor authentication for SSH logins using PAM and Google Authenticator. Secure your servers with time-based one-time passwords alongside SSH keys.
Detailed Explanation
Adding TOTP to SSH Authentication
Securing SSH access with TOTP adds a second factor beyond passwords or SSH keys. The most common approach on Linux uses Google Authenticator PAM module (libpam-google-authenticator), which integrates TOTP verification into the SSH login process.
Installation
On Debian/Ubuntu:
sudo apt-get install libpam-google-authenticator
On RHEL/CentOS:
sudo yum install google-authenticator
Per-User Setup
Each user runs the setup command:
google-authenticator
This interactive wizard:
- Generates a new TOTP secret
- Displays a QR code in the terminal (ASCII art)
- Provides emergency backup codes
- Asks configuration questions (time-based, window size, rate limiting)
- Writes
~/.google_authenticatorwith the secret and settings
PAM Configuration
Edit /etc/pam.d/sshd to add the authenticator module:
auth required pam_google_authenticator.so
Place this line after @include common-auth for password + TOTP, or configure it alongside SSH key authentication.
SSH Server Configuration
Edit /etc/ssh/sshd_config:
ChallengeResponseAuthentication yes
UsePAM yes
AuthenticationMethods publickey,keyboard-interactive
The AuthenticationMethods line requires both an SSH key and a TOTP code. Restart sshd after changes:
sudo systemctl restart sshd
Authentication Flow
After configuration, SSH login proceeds as:
- Client presents SSH public key (verified against
authorized_keys) - Server prompts for verification code
- User enters the current TOTP code from their authenticator app
- Both factors verified → access granted
Important Considerations
- Test in a separate session before logging out — misconfiguration can lock you out
- Keep a root console open during setup for emergency access
- Backup the secret file (
~/.google_authenticator) alongside your SSH keys - Service accounts may need exemption from TOTP (use
Match Userin sshd_config) - Automated scripts that use SSH will need alternative authentication paths
Use Case
System administrators securing production servers need TOTP as a second factor for SSH access, especially when compliance frameworks (SOC 2, PCI DSS, ISO 27001) require multi-factor authentication for administrative access. This guide is essential when hardening server access controls, setting up bastion hosts with 2FA, or responding to audit findings that recommend MFA for all SSH sessions.