How to Set Up Two-Factor Authentication for SSH
Two-factor authentication (2FA) adds an extra layer of security to SSH by requiring a verification code in addition to the configured SSH authentication method.
Make sure you have an active SSH session or console access before you change authentication settings. An incorrect PAM or SSH configuration can prevent you from logging in. Keep your current SSH session open until you have confirmed that you can log in with the new configuration.
Configure the Server
Install the EPEL repository
Install the Extra Packages for Enterprise Linux (EPEL) repository. When prompted for confirmation, type y and press Enter.
Output:
Install Google Authenticator
Install the Google Authenticator PAM module. When prompted for confirmation, type y and press Enter.
Output:
Initialize Google Authenticator
Run the following command:
The command asks several questions. Answer as shown:
Save the secret key and scratch codes
The command prints a secret key, a verification code and emergency scratch codes. Save the secret key and the scratch codes securely. You need the secret key to set up the mobile authenticator app, and the scratch codes let you log in if you lose your phone.
Example:
The secret key and scratch codes above are examples only. Do not use them on a real server.
Configure the SSH PAM file
Open the SSH PAM configuration file:
Find the following line and comment it out:
It should now read:
Add the following lines at the bottom of the file, then save it:
Configure OpenSSH
Open the SSH configuration file:
Find the ChallengeResponseAuthentication setting. Comment out the no setting and enable the yes setting:
Add the following lines at the bottom of the file, then save it:
Restart the SSH service
Restart the SSH service. Keep your current session open.
Set Up the Google Authenticator Mobile App
Install the app
Download Google Authenticator from the Play Store and open it.
Add the account
Select the Add button, then select Enter a provided key.
Enter the key
Enter the account name and the secret key generated during the Google Authenticator setup. Select Time-based, then click Add.
Test the login
Keep your current session open and open a new SSH connection. SSH asks for a verification code. Enter the current code shown in the Google Authenticator app.

