How to setup two factor authentication by using Google Authenticator on SSH

Using SSH can protect you against inadvertently using weak passwords that can lead to a successful brute force attack. This guide shows you how to implement Google Authenticator on servers that are running RedHat, CentOS and Ubuntu Linux distributions.

Important : After you complete the steps in this guide, all of your users (including root) must use Google Authenticator to connect through SSH unless you already have SSH keys in place. Check with your administration teams before setting up Google Authenticator to ensure that you don’t accidentally disable their access or lock yourself out from using SSH.

To install the Google Authenticator module, open a command-line interface (CLI) and follow the instructions that correspond to your distribution.

Install the module on Red Hat, CentOS by running the following commands:

yum install google-authenticator

Install the module on Ubuntu, Debian by running the following command:

apt install libpam-google-authenticator

If you can’t find the package google-authenticator you can ask her for help.

Open the /etc/pam.d/sshd file and add the following line at the end of the auth section:

auth required pam_google_authenticator.so

Open your /etc/ssh/sshd_config file and change ChallengeResponseAuthentication no to ChallengeResponseAuthentication yes.

Use the following command to restart sshd :

#For rpm on Red Hat, CentOS:
systemctl restart sshd

#For deb on Ubuntu, Debian:
systemctl restart sshd

Set up keys for the user

Use the following steps to set up keys for the user:

Run the following command:

google-authenticator

Answer yes when you are prompted to update your ~/.google_authenticator file and provide answers to the next three prompts.

After you complete these steps, you see the following information:

  • New secret key
  • Verification code
  • Emergency scratch codes

Use the new secret key to add the account to your phone’s Google Authenticator app. Note the emergency scratch codes and store them somewhere secure. You can use them if you lose your smart phone or otherwise need to log in to your account without using your Google Authenticator App.

Now when you log in to your server under your user account, you are prompted for your Google authentication token and your standard password for the server. Any accounts that don’t have this setup are not allowed to log in.

Here you have an example:

$ ssh root@example.com
Verification code:

root@example:~#