Introduction
Securing your SSH access is crucial for maintaining the integrity of your Linux server. While password authentication is common, it's vulnerable to brute-force attacks. Multi-Factor Authentication (MFA) using Google Authenticator adds an extra layer of security by requiring a time-based one-time password (TOTP) in addition to your regular credentials.
In this comprehensive guide, I'll walk you through setting up Google Authenticator for SSH login on your Linux server.
Prerequisites
Before we begin, make sure you have:
- Root or sudo access to your Linux server
- An active SSH connection to your server
- A smartphone with Google Authenticator app installed (Android / iOS)
- Basic knowledge of Linux command line
⚠️ Important Warning: Keep your current SSH session open throughout this process. Open a second terminal window for testing to avoid locking yourself out.
Step 1: Update Your System
First, ensure your system packages are up to date:
sudo apt update && sudo apt upgrade -y # For Debian/Ubuntu
For CentOS/RHEL/Fedora:
sudo yum update -y # CentOS/RHEL 7
sudo dnf update -y # CentOS/RHEL 8+ / Fedora
Step 2: Install Google Authenticator PAM Module
Install the Google Authenticator PAM (Pluggable Authentication Module):
For Debian/Ubuntu:
sudo apt install libpam-google-authenticator -y
For CentOS/RHEL/Fedora:
sudo yum install google-authenticator -y # CentOS/RHEL 7
sudo dnf install google-authenticator -y # CentOS/RHEL 8+ / Fedora
You can verify the installation:
which google-authenticator
This should return the path: /usr/bin/google-authenticator
Step 3: Configure Google Authenticator for Your User
Run the Google Authenticator setup for your user account:
google-authenticator
You'll be asked several questions. Here are the recommended answers:
Question 1: Time-based tokens
Do you want authentication tokens to be time-based? (y/n)
Answer: y (Yes - this enables TOTP)
After answering yes, you'll see:
- A large QR code in your terminal
- Your secret key
- Verification code
- Emergency scratch codes
📱 Scan the QR code with your Google Authenticator app, or manually enter the secret key if the QR code doesn't scan.
💾 Save the emergency scratch codes in a secure location! These are one-time use backup codes if you lose access to your phone.
Question 2: Update configuration file
Do you want me to update your "~/.google_authenticator" file? (y/n)
Answer: y (This saves your configuration)
Question 3: Disallow multiple uses
Do you want to disallow multiple uses of the same authentication token? (y/n)
Answer: y (Prevents replay attacks)
Question 4: Time skew
By default, tokens are good for 30 seconds. Do you want to increase the time window? (y/n)
Answer: n (Keep the default 30-second window for better security)
Question 5: Rate limiting
Do you want to enable rate-limiting? (y/n)
Answer: y (Protects against brute-force attacks - allows 3 login attempts per 30 seconds)
Step 4: Configure SSH to Use Google Authenticator
Now we need to configure PAM and SSH to use Google Authenticator.
4.1: Edit PAM Configuration
Open the PAM SSH configuration file:
sudo nano /etc/pam.d/sshd
Add this line at the top of the file:
auth required pam_google_authenticator.so
Optional but recommended: Comment out the common-auth line to disable password authentication and only use 2FA + SSH keys:
# @include common-auth
Note: If you comment this out, you'll need SSH key authentication set up, otherwise you'll only need the 2FA code.
Save and exit (Ctrl+X, then Y, then Enter).
4.2: Configure SSH Daemon
Edit the SSH daemon configuration:
sudo nano /etc/ssh/sshd_config
Find and modify these lines:
# Change this from 'no' to 'yes'
ChallengeResponseAuthentication yes
For newer SSH versions (OpenSSH 9.x+), you might need:
KbdInteractiveAuthentication yes
For even stronger security (2FA + SSH keys), add:
AuthenticationMethods publickey,keyboard-interactive
This requires both SSH key authentication AND the 2FA code.
If you want 2FA or SSH key (either one), use:
AuthenticationMethods publickey keyboard-interactive
Also ensure:
UsePAM yes
Save and exit.
Step 5: Restart SSH Service
⚠️ Critical: Before restarting, ensure you have a backup session open!
Restart the SSH service:
For systems with systemd (Ubuntu 16.04+, CentOS 7+, Debian 8+):
sudo systemctl restart sshd
For older systems:
sudo service ssh restart # Debian/Ubuntu
sudo service sshd restart # CentOS/RHEL
Check the service status:
sudo systemctl status sshd
Step 6: Test Your Configuration
Keep your existing SSH session open! Open a new terminal and try to connect:
ssh username@your-server-ip
You should see prompts for:
- Your password (if not using SSH keys only)
- Verification code (from Google Authenticator app)
Enter the 6-digit code from your Google Authenticator app.
If successful, you'll be logged in! 🎉
Troubleshooting
Issue 1: Locked Out of Server
Prevention is key! Always keep a session open while configuring.
If locked out and you have console access (VPS panel, cloud provider console):
- Access via console
- Edit
/etc/pam.d/sshdand comment out:
# auth required pam_google_authenticator.so
- Restart sshd:
sudo systemctl restart sshd
Issue 2: "Invalid Verification Code" Error
Cause: Time synchronization issues.
Solution: Ensure your server's time is synchronized:
sudo timedatectl set-ntp true
sudo systemctl restart systemd-timesyncd
timedatectl status
For older systems:
sudo ntpdate pool.ntp.org
Issue 3: Emergency Access
If you lose your phone, use one of the emergency scratch codes you saved earlier. Each code can only be used once.
Issue 4: Multiple Users
Each user must run google-authenticator separately to set up their own 2FA. The configuration is stored per-user in ~/.google_authenticator.
Issue 5: SSH Keys Not Working
If you configured AuthenticationMethods publickey,keyboard-interactive and SSH keys aren't working:
- Verify your public key is in
~/.ssh/authorized_keys - Check permissions:
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
- Check SSH logs:
sudo tail -f /var/log/auth.log # Debian/Ubuntu
sudo tail -f /var/log/secure # CentOS/RHEL
Security Best Practices
- Save Emergency Codes Securely: Store scratch codes in a password manager or secure location
- Use Strong Passwords: Even with 2FA, maintain strong password practices
-
Regular Backups: Back up your
~/.google_authenticatorfile securely -
Monitor Logs: Regularly check
/var/log/auth.logfor suspicious activity - Combine with SSH Keys: Use both SSH keys and 2FA for maximum security
-
Disable Root Login: In
/etc/ssh/sshd_config, setPermitRootLogin no - Change Default Port: Consider changing SSH from port 22 to reduce automated attacks
- Use Fail2Ban: Install fail2ban to automatically block repeated failed login attempts
Useful Commands
Regenerate 2FA for current user:
google-authenticator -f
View your configuration:
cat ~/.google_authenticator
Disable 2FA temporarily (for current user):
mv ~/.google_authenticator ~/.google_authenticator.backup
Re-enable:
mv ~/.google_authenticator.backup ~/.google_authenticator
Check SSH authentication logs:
sudo grep sshd /var/log/auth.log | tail -20
Conclusion
Congratulations! You've successfully set up Google Authenticator for SSH on your Linux server. Your server is now protected by two-factor authentication, significantly reducing the risk of unauthorized access.
Key Takeaways:
- Always test in a separate terminal before closing your original session
- Save emergency scratch codes in a secure location
- Keep your server's time synchronized
- Consider combining 2FA with SSH key authentication for maximum security
Remember, security is an ongoing process. Regularly review your server logs, keep your system updated, and follow security best practices.
Have questions or run into issues? Drop a comment below, and I'll be happy to help! 👇
Did this guide help you? Give it a ❤️ and share it with others who might find it useful!
Top comments (0)