How To Set Up 2FA for SSH on CentOS 7 and Ubuntu

Step 1: Install and Configure Google Authenticator on Ubuntu Server and CentOS

Log into your server and run the following command to install Google Authenticator from the default Ubuntu package repository.

Ubuntu:
sudo apt install libpam-google-authenticator

Centos:
yum install google-authenticator

if this command is not working intall epel-release and try again.

Then run the google-authenticator command to create a new secret key in your home directory.

google-authenticator

When asked “Do you want authentication tokens to be time-based?” Answer y . Then You will be shown a QR code that you can scan using the Google Authenticator mobile app.

Install Google Authenticator app via Google play or Apple app store on your mobile phone and scan the QR code. The QR code represents the secret key, which is only known by your SSH server and your Google Authenticator app. Once the QR code is scanned, you can see a six-digit one-time password on your phone. By default it lasts for 30 seconds.

google-authenticator-ssh-ubuntu-203x360

You can see the secret key, verification code and emergency scratch code in the terminal window. It’s recommended to save these information to a safe place for later use.

Then you can enter y to answer all of the remaining questions. This will update you Google Authenticator configuration file, disable multiple uses of the same authentication token, increase the time window and enable rate-limiting to protect against brute-force login attempts.

Step 2: Configure SSH Daemon to Use Google Authenticator

Open SSH server configuration file.

sudo nano /etc/ssh/sshd_config

PAM stands for pluggable authentication module. It provides an easy way to plug different authentication method into your Linux system. To enable Google Authenticator with SSH, PAM and Challenge-Response authentication must be enabled. So find the following two lines in the file, and make sure both of them is set to yes .

UsePAM yes 
ChallengeResponseAuthentication yes

Save and close the file. Then restart SSH daemon.

sudo systemctl restart ssh

Next, edit the PAM rule file for SSH daemon.

sudo vi /etc/pam.d/sshd

Add the following entry at the end of the file.

auth required pam_google_authenticator.so

Save and close the file. From now on SSH daemon will use Google Authenticator.

Step 3: Test Your SSH Two Factor Authentication

Now open a separate terminal window and try logging into your SSH server. Do not close your current SSH session. If something goes wrong, you can fix it in your current SSH session. If everything is set up correctly, you will be asked to enter both your user password and the one time password.

Also note that each user on your Ubuntu or CentOS server needs to run google-authenticator command and scan QR code in order to use two-factor authentication.