Two-factor authentication (2FA) adds an extra layer of protection to your server by requiring not only your username and password but also a time-based one-time code generated on your mobile device. This makes brute-force attacks and unauthorized access much more difficult.
About Two-Factor Authentication
By default, SSH logins require only a username and password. With 2FA enabled, you’ll also need a temporary numeric code generated by an authenticator app (such as Google Authenticator or Authy). This ensures that even if your password is compromised, attackers cannot log in without your mobile device.
Prerequisites
-
Root access to your server.
-
SSH access enabled.
-
An authenticator app installed on your smartphone (Google Authenticator, Authy, Microsoft Authenticator, etc.).
Steps to Enable 2FA for SSH
Step 1: Disable Root Logins (Recommended)
For best security, disable direct root logins and create a normal user account with sudo privileges. (See our article on Disabling SSH logins for the root account for details.)
Step 2: Install Google Authenticator on the Server
Log in to your server via SSH as root and install the required package:
-
Debian/Ubuntu:
Bash apt-get install libpam-google-authenticator -
AlmaLinux/Fedora:
Bash yum install google-authenticator
Step 3: Configure Google Authenticator
-
While logged in as your non-root user, run:
Bash yum install google-authenticator -
Answer the prompts:
-
Time-based tokens? →
y -
Update .google_authenticator file? →
y -
Disallow multiple uses of the same token? →
y -
Increase token validity window? →
n(default is more secure) -
Enable rate-limiting? →
y
-
-
A QR code and secret key will be displayed.
-
Scan the QR code with your authenticator app.
-
Save the emergency backup codes in a safe place.
-
Step 4: Update PAM and SSH Configuration
-
Edit the PAM SSH file:
Bash nano /etc/pam.d/sshdAdd this line at the top:
Bash auth required pam_google_authenticator.so nullok -
Edit the SSH configuration file:
nano /etc/ssh/sshd_configFind and change:
ChallengeResponseAuthentication yes -
Restart SSH:
-
Debian/Ubuntu:
Bash service ssh restart -
AlmaLinux/Fedora:
Bash service sshd restart
-
Step 5: Test the Configuration
-
Open a new terminal and log in as your non-root user.
-
You should be prompted for:
-
Verification code (from your authenticator app).
-
Password (your user password).
-
Do not close your root session until you confirm the new login works.
Disabling 2FA for SSH
If you need to disable 2FA:
-
Remove or comment out the
pam_google_authenticator.soline in/etc/pam.d/sshd. -
Set
ChallengeResponseAuthentication noin/etc/ssh/sshd_config. -
Restart the SSH service.