An Authentication factor is a piece of information that proves you have the rights to logging into a system, SSH uses password authentication by default and it’s not good because it’s just a single factor, so if somehow your password has been compromised then there is nothing to stop the bad actor from owning your system. and this is what we call “Single Point of Failure”.
In this tutorial, we are going to set up the Two-Step Authentication using Google-Authenticator mobile app which gives you a One-Time-Password (OTP) each time you are logging into your system.
Install the Google-Authenticator
Google-Authenticator app is available on all of the mobile phones, you can download the Android app from Google Play and the IOS app (iPhone users) from the App Store.
Installing Google’s PAM
PAM (Pluggable Authentication Module) is authentication infrastructure based on Linux system to authenticate a user.
First of all install EPEL repository with the following command:
yum install epel-release
Now install the Google’s PAM:
yum install google-authenticator
Configuring Google’s PAM
After the installation process is finished, you can run the script which helps you generate a key for the user you want to add a second factor for, this key is generated on a user-based system not system-wide, this means every user that wants to use an OTP auth will need to log in and run the generator script to get their own key.
Execute the following command to run the initialization script:
After you run the command, you’ll be asked a few questions. The first one asks if authentication tokens should be time-based. it’s recommended to answer with “Y”.
After that, a huge QR code will appear on your terminal which you have to scan it with your Phone so the profile automatically adds to your Google-Authenticator app.
And also make sure to write down the “secret key”, “verification code”, and “emergency scratch codes” So if you lost your phone or accidentally remove the Application from it you will be able to log in to your server.
Now you will be prompt for some questions which inform PAM how to function, go ahead and answer them with “Y” or “N” and it’s pretty easy to choose whats best for you.
After you answered all the questions, your Google’s PAM is ready and configured. now we just have to do some configuration for our SSH.
Open up the SSH configuration file with the following command:
Add the following line at the very end of the file:
auth required pam_google_authenticator.so nullok
Now we will configure SSH to support this kind of authentication, Open the “sshd_config” file with the command below:
Look for the line that refers to “ChallengeResponseAuthentication” and set its value to “yes”. like below:
Restart your SSH service and you are good to go:
systemctl restart sshd
From now on you will be asked for a “Verification-code”, which you have to get if from your Google-Authenticator app form your phone.