Two-Factor Authentication (2FA) adds an extra layer of protection to your VPS by requiring both your password and a time-based verification code. Even if someone obtains your SSH password, they won't be able to access your server without your mobile authentication code.
This guide explains how to enable Google Authenticator-based Two-Factor Authentication for SSH on Ubuntu 22.04 and Ubuntu 24.04.
Requirements
- Ubuntu 22.04 or Ubuntu 24.04 VPS
- Root or sudo privileges
- OpenSSH Server installed
- Google Authenticator or Microsoft Authenticator app on your smartphone
Step 1: Update Your VPS
sudo apt update
sudo apt upgrade -y
Step 2: Install Google Authenticator
sudo apt install libpam-google-authenticator -y
Step 3: Configure Your User
google-authenticator
Answer the setup questions as follows:
- Generate authentication tokens: Yes
- Update the configuration file: Yes
- Disallow multiple uses of the same token: Yes
- Increase protection against brute-force attacks: Yes
- Enable rate limiting: Yes
A QR code will appear. Scan it using Google Authenticator or Microsoft Authenticator.
Step 4: Configure PAM
Edit the SSH authentication configuration:
sudo nano /etc/pam.d/sshd
Add the following line at the end of the file:
auth required pam_google_authenticator.so
Step 5: Configure SSH
Edit the SSH configuration file:
sudo nano /etc/ssh/sshd_config
Make sure these options are set:
ChallengeResponseAuthentication yes
KbdInteractiveAuthentication yes
UsePAM yes
Then restart SSH:
sudo systemctl restart ssh
Step 6: Test Your Login
Open a new SSH session.
After entering your password, you'll be prompted for a verification code generated by your authenticator app.
Backup Emergency Codes
During setup, Google Authenticator generates emergency recovery codes.
Store these codes securely. They allow access if your mobile device is lost or damaged.
Security Best Practices
- Use SSH public key authentication.
- Disable direct root login.
- Install Fail2Ban to block brute-force attacks.
- Keep Ubuntu updated regularly.
- Allow SSH access only from trusted IP addresses whenever possible.
Why Enable Two-Factor Authentication?
- Protects against stolen passwords.
- Greatly reduces unauthorized SSH access.
- Works with free authenticator apps.
- Takes only a few minutes to configure.
- Recommended for all production VPS servers.
Conclusion
Adding Two-Factor Authentication to your Ubuntu VPS is one of the simplest and most effective ways to improve server security. When combined with SSH keys, Fail2Ban, firewall rules, and regular updates, it creates a strong defense against unauthorized access.
If you need a secure VPS with full root access, dedicated IPv4, NVMe storage, instant deployment, and cryptocurrency payment options, VPS For Life provides reliable Linux VPS solutions for developers, businesses, and system administrators worldwide.
