RHEL 7 Two-Factor SSH Via Google Authenticator


In this post,  I am going to walk you through the process of installing and configuring two- factor SSH authentication via Google Authenticator. My base system is running a fresh install of RHEL 7.2

Installation Steps

The first step on my system was to install autoreconf, automake, and libtool. These packages are required by the bootstrap.sh script that we will need to in a couple more steps.

# yum -y install autoconf automake libtool

Now, we are going to install Git.

#yum -y install git

One more dependency to knock out. Install pam-devel as shown below.

# yum -y install pam-devel

Next, we clone the google-authenticator Git repo. In this example, I am cloning to /root

# git clone https://github.com/google/google-authenticator.git
Cloning into ‘google-authenticator’…
remote: Counting objects: 1435, done.
remote: Total 1435 (delta 0), reused 0 (delta 0), pack-reused 1435
Receiving objects: 100% (1435/1435), 2.32 MiB | 0 bytes/s, done.
Resolving deltas: 100% (758/758), done.

Now change directory as shown below and run bootstrap.sh.

# cd /root/google-authenticator/libpam

# ./bootstrap.sh

Now run the following commands to finalize the module installs.

# ./configure


#make install

Assuming that you do not run into any errors, the following modules will be installed.

  • /usr/local/lib/security/pam_google_authenticator.so
  • /usr/local/lib/security/pam_google_authenticator.la


Global Configuration

Before we start slapping around some pam modules, let’s be smart and make a backup.

# cd /etc/pam.d ; mkdir ARCHIVE
# cp sshd ARCHIVE/sshd

Now let’s edit /etc/pam.d/sshd. Here is the auth section of my file. This configuration will not prompt for a verification code if the user is using an SSH key. If this behavior is undesirable, move the “password-auth”  below the “pam_google_authenticator.so” line.

auth     required     pam_sepermit.so
auth     substack     password-auth
auth     required     /usr/local/lib/security/pam_google_authenticator.so
auth     include      postlogin

Now we edit /etc/ssh/sshd_config and change the line below t0 yes.

ChallengeResponseAuthentication yes

Now restart sshd.

Note, do not lock yourself out of your system. Make sure that you are logged in as root and do not disconnect. 

#systemctl restart sshd.service.

User Configuration Steps

Ok, now we are almost done. In order to use two-factor google authentication, each user must run the google-authenticator command individually. This will generate a QR code that each user can scan into their google-authenticator app. You can download the Android app here.

Now for testing, I have created a user ‘fatmin‘. As this user, I will run the command as shown.

# google-authenticator

At this point you will be prompted to answer the questions below. I have answered yes to each question.

Do you want authentication tokens to be time-based (y/n) y

Do you want me to update your “/home/fatmin/.google_authenticator” file (y/n) y

Do you want to disallow multiple uses of the same authentication
token? This restricts you to one login about every 30s, but it increases
your chances to notice or even prevent man-in-the-middle attacks (y/n) y

By default, tokens are good for 30 seconds. In order to compensate for
possible time-skew between the client and the server, we allow an extra
token before and after the current time. If you experience problems with
poor time synchronization, you can increase the window from its default
size of +-1min (window size of 3) to about +-4min (window size of
17 acceptable tokens).
Do you want to do so? (y/n) y

If the computer that you are logging into isn’t hardened against brute-force
login attempts, you can enable rate-limiting for the authentication module.
By default, this limits attackers to no more than 3 login attempts every 30s.
Do you want to enable rate-limiting (y/n) y

Now scan the QR code with the google authenticator app on your phone. This will create an entry for “fatmin@myserver”

Now attempt to ssh into your server. Enter your password when prompted and your Google Verification Code when prompted. See below.

$ ssh fatmin@
Verification code:

At this point, you should be able to log in. If you are having issues,  monitor “/var/log/secure” for errors. You can also change the order of modules in your PAM configuration if you would rather prompt users for their “Verification code” before their password.

Additional Security Steps

Here are a few additional steps you can take to further secure your server. Feel free to suggest more.

Disable Root Logins Via SSH

I also suggest disabling root logins via ssh. You can do so by editing /etc/ssh/sshd_config and change “Yes” no “No“. Don’t forget to restart or reload sshd.

# grep Root /etc/ssh/sshd_config
#PermitRootLogin yes

Install Fail2ban

“Fail2ban is an intrusion prevention software framework that protects computer servers from brute-force attacks”.


#yum -y install fail2ban

Create a local config file

# cat /etc/fail2ban/jail.local
# Ban hosts for one hour:
bantime = 3600

# Override /etc/fail2ban/jail.d/00-firewalld.conf:
banaction = iptables-multiport

enabled = true

Start and enable.

#systemctl enable fail2ban
Created symlink from /etc/systemd/system/multi-user.target.wants/fail2ban.service to /usr/lib/systemd/system/fail2ban.service.
# systemctl start fail2ban
# systemctl status fail2ban

Configure Iptables to Block China

I like to be able to ssh into my server when I travel (I have forwarded ssh traffic from my router), but I only travel within North America. No need to allow possible connections from China. We can block them with our system firewall.

I prefer Iptables over Firewalld, so let’s disable Firewalld.

# systemctl stop firewalld
# systemctl disable firewalld
Removed symlink /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
Removed symlink /etc/systemd/system/basic.target.wants/firewalld.service.

Now let’s install Iptables

# yum -y install iptables.x86_64 iptables-services.x86_64

Now we need to enable and start Iptables

# systemctl enable iptables
Created symlink from /etc/systemd/system/basic.target.wants/iptables.service to /usr/lib/systemd/system/iptables.service.
# systemctl start iptables

I grabbed my blacklist rules from here. I dumped the list out to a file and formatted the list so that I could insert it into my Iptables config.

Then restart Iptables.

# systemctl restart iptables

Feel free to block other countries as you see fit. This guy has a few more lists here.



11 thoughts on “RHEL 7 Two-Factor SSH Via Google Authenticator

  1. Great walk through. I had to add the following line to my /etc/ssh/sshd_config file to get the Google module to work (with PKI auth):
    AuthenticationMethods publickey,keyboard-interactive

  2. Pingback: SSH 접속에 Google OTP 인증을 추가하는 방법을 정리하였습니다. - 소소한 일상 블로그

  3. Followed same process m getting access denied:

    login as: XXXX
    Authenticating with public key “imported-openssh-key”
    Further authentication required
    Using keyboard-interactive authentication.
    Verification code:
    Access denied

    Please help me on this. Using RHEL 7.5 AMI.

    • found in secure log:

      sshd(pam_google_authenticator)[6902]: Accepted google_authenticator for testuser1
      sshd(pam_google_authenticator)[6902]: Failed to delete tempfile “/home/testuser1/.google_authenticator~Q6SNiK”: No such file or directory
      sshd(pam_google_authenticator)[6902]: Failed to update secret file “/home/testuser1/.google_authenticator”: Permission denied
      sshd[6900]: error: PAM: Authentication failure for testuser1 from XXX.XXX.XX.XX

      .google_authenticator has 600 permission. tried of providing different permissions. still no luck. Please help

      • So what are the current perms on /home/testuser1 and the .google_authenticator file?

        I currently have these perms on .google_authenticator

        -r——– 1 cpaquin cpaquin 225 Jan 14 2018 .google_authenticator

        Perms on my home directory are as follows.

        ls -ld /home/cpaquin/

        drwx——. 3 cpaquin cpaquin 4096 May 29 12:25 /home/cpaquin/

        Also worth noting that I have selinux disabled, so its possible that if your permissions are correct the selinux context needs to be set on .google_authenticator. You might try disabling SElinux as part of troubleshooting.

  4. i have same home folder permissions and disabled SElinux too. please find all detials and debug logs:

    /var/log/secure : debug log =>
    sshd(pam_google_authenticator)[4498]: debug: no scratch code used from “/home/testuser1/.google_authenticator”
    sshd(pam_google_authenticator)[4498]: Accepted google_authenticator for testuser1
    sshd(pam_google_authenticator)[4498]: Failed to create tempfile “/home/testuser1/.google_authenticator~1lqc2M”: Permission denied
    sshd(pam_google_authenticator)[4498]: Failed to update secret file “/home/testuser1/.google_authenticator”: Permission denied
    sshd(pam_google_authenticator)[4498]: debug: end of google_authenticator for “testuser1”. Result: Authentication failure
    sshd[4493]: error: PAM: Authentication failure for testuser1 from x.x.x.x
    sshd(pam_google_authenticator)[4499]: debug: start of google_authenticator for “testuser1”
    sshd(pam_google_authenticator)[4499]: debug: Secret file permissions are 0600. Allowed permissions are 0600
    sshd(pam_google_authenticator)[4499]: debug: “/home/testuser1/.google_authenticator” read
    sshd(pam_google_authenticator)[4499]: debug: shared secret in “/home/testuser1/.google_authenticator” processed
    sshd[4493]: Postponed keyboard-interactive for testuser1 from x.x.x.x port 54109 ssh2 [preauth]

    ls -ld /home/testuser1/ =>
    drwx——. 3 testuser1 testuser1 124 Jul 18 09:54 /home/testuser1/

    ls -ld /home/testuser1/.google_authenticator
    -rw——-. 1 testuser1 testuser1 136 Jul 18 09:54 /home/testuser1/.google_authenticator

    /etc/selinux/config =>

    /etc/pam.d/sshd =>
    auth required pam_sepermit.so
    ##auth substack password-auth
    auth required /usr/local/lib/security/pam_google_authenticator.so debug echo_verification_code
    auth include postlogin

    /etc/ssh/sshd_config =>
    ChallengeResponseAuthentication yes
    AuthenticationMethods publickey,keyboard-interactive

  5. how uninstall the perfomed activity from the server

    #yum -y install git

    # yum -y install pam-devel

    # git clone https://github.com/google/google-authenticator.git
    Cloning into ‘google-authenticator’…
    remote: Counting objects: 1435, done.
    remote: Total 1435 (delta 0), reused 0 (delta 0), pack-reused 1435
    Receiving objects: 100% (1435/1435), 2.32 MiB | 0 bytes/s, done.
    Resolving deltas: 100% (758/758), done


    Please advice

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.