Securing SSH with two factor authentication using Google Authenticator

Two-step verification (also known as Two-factor authentication, abbreviated to TFA) is a process involving two stages to verify the identity of an entity trying to access services in a computer or in a network. This is a special case of a multi-factor authentication which might involve only one of the three authentication factors (a knowledge factor, a possession factor, and an inheritance factor) for both steps. If each step involves a different authentication factor then the two-step verification is additionally two-factor authentication.

Google’s two-step verification process

Google was one of the first Internet companies to introduce a two-step verification process. To access a Google service using the two-step verification process, a user has to go through the following two stages:

The first step is to log in using the username and password. This is an application of the knowledge factor.
The implementation of the second step requires a mobile phone or the Google Authenticator application, which is an application of the possession factor.

If the user opts to use a mobile phone, he/she has to register his/her phone number with Google. When one attempts to authenticate with username and password, Google will send via SMS a new, unique code to the phone. Receiving the SMS demonstrates that the user has the phone (or, in the case of GSM like networks the appropriate SIM chip).

If the user opts to use the Google Authenticator (or another supported code generator application), he/she simply opens the application, which generates a new code every 30 seconds. This code is to be entered to complete the log in process. As a backup option in case the registered mobile phone or device running Google Authenticator is lost, stolen, or otherwise unavailable, the user can print a set of static single-use backup codes (also the knowledge factor) and store them in a safe place.

The following are some other sites which offer two-step verification service:

  1. Amazon Web Services15 - Securing SSH with two factor authentication using Google Authenticator - blackMORE Ops
  2. ANX
  4. Apple ID
  5. Authy
  7. Bitstamp
  9. Box
  10. Dropbox
  11. eBay
  12. Etrade
  13. Evernote
  14. Facebook
  15. GitHub
  16. GoDaddy
  17. HootSuite
  18. Lastpass
  19. LinkedIn
  20. LocalBitcoins
  21. Microsoft
  22. MongoLab
  23. Namecheap
  24. PayPal
  25. SocialFlow
  26. timetotrade
  27. Tumblr
  28. Twitter
  29. Viaduct
  30. WordPress
  31. Yahoo! Mail
  33. zoho

Google Authenticator

Google Authenticator implements TOTP security tokens from RFC6238 in mobile apps made by Google, sometimes branded “two-step authentication”. The Authenticator provides a six digit one-time password users must provide in addition to their username and password to log into Google services or other sites. The Authenticator can also generate codes for third party applications, such as password managers or file hosting services. Some versions of the software are open source.
[Source: WikiPedia]

Note: Google Authenticator doesn’t “call home” to Google — all the work happens on your SSH server and your phone. Google Authenticator is a open-source software, that means you can check the codes yourself. I guess after what happened with openSSL, that’s not a bad idea after all.

In this article I will demonstrate how to secure SSH by setting up Two Factor Authentication (TFA) with Google Authenticator for the following Linux operating systems:

  1. Debian
  2. Ubuntu
  3. Linux Mint
  4. Kali Linux
  5. Red Hat
  6. CentOS
  7. Fedora

Google Authenticator can be used in the following smartphones:

  1. Android,
  2. iOS and
  3. Blackberry.

I am not too sure if you can use this on a Windows Based phone (i.e. new Nokia phones or Windows Mobiles devices). Feel free to try and report back.

App Download Links as follows:

  1. Android:
  2. iOS:
  3. Blackberry:

More detailed per device install instructions can be found on this page:

The implementation is exactly same except for some package name differences. So you can implement this in any Linux Operating System that uses these packages.


Followings are the requirements for using Google Authenticator on your system:

  1. A PC running Linux
  2. A smartphone
  3. A running SSH server on your machine.

In case you don’t have SSH server running, just follow this guide to install openSSH server.

Step 1: Install dependencies for Google Authenticator Module

You need to have either root or sudo privileges on the machine where you want to secure SSH by enabling Two Factor Authention using Google Authenticator. Login to your machine and use the following commands to install required dependency packages:

On Debian, Kali, Ubuntu, Linux Mint (they all are Debian based system that uses aptitude as package manager i.e. apt-get/aptitude)

apt-get install libpam0g-dev

1 - Install dependencies for Google Authenticator PAM module - blackMORE Ops

On Red Hat, CentOS and Fedora (they all are RedHat based where you use yum as the package manager):

yum install pam-devel

That’s it. That should install the necessary dependencies on your system. In case you have a very restricted system where you dont have GCC, make and wget, you can install them using the following command(s):

yum install make gcc wget
apt-get install make gcc wget

Step 2: Download Google Authenticator Module

Google Authenticator is available on GoogleCode website.


You can just copy paste the codes below to download and extract Google Authenticator codes. I personally use Kali Linux, that means I am always logged in as root user, if you’re using any of the other Linux distributions like Debian, Ubuntu, Linux Mint, Red Hat, CentOS or Fedora where you don’t usually login as root user, then you should choose your own directory to download and extract these codes.

To download Source code of the Google Authenticator PAM library module use the following command:

root@kali:~# wget

At the time of writing this article, v1.0 was available.

2 - Download Google Authenticator PAM module from GoogleCode - blackMORE Ops

Now extract your tarball:

root@kali:~# tar -xvf libpam-google-authenticator-1.0-source.tar.bz2

Change directory to the extracted folder:

root@kali:~# cd libpam-google-authenticator-1.0/

3 - Extract Google Authenticator PAM module from GoogleCode - blackMORE Ops

Step 3: Compile and Install Google Authenticator PAM module

So far we’ve installed dependencies, downloaded and extracted Google Authenticator PAM module. Now we need to compile the codes and install compiled software on our system.
use the following command to compile your downloaded source codes:

root@kali:~/libpam-google-authenticator-1.0# make

4 - Compile extracted Google Authenticator PAM module from GoogleCode - blackMORE Ops

Now install Google Authenticator PAM module on your system:

root@kali:~/libpam-google-authenticator-1.0# make install

5 - Install compiled Google Authenticator PAM module from GoogleCode - blackMORE Ops

Step 4: Run and configure Google Authenticator

Just run Google Authenticator PAM module from command line to configure it for your system:

Run Google Authenticator PAM module using the following command:

root@kali:~/libpam-google-authenticator-1.0# google-authenticator

It should present you with bunch of question where you get to choose Y or N . Let’s have a quick look at those questions and the outputs.

Do you want authentication tokens to be time-based (y/n) y|0&cht=qr&chl=otpauth://totp/root@kali%3Fsecret%3DWKHM6UVJNTPYSPTQ
Your new secret key is: WKHM6UVJNTPYSPTQ
Your verification code is 434260
Your emergency scratch codes are:

So on your first question, you get a secret key, Your new secret key is: WKHM6UVJNTPYSPTQ and 5 emergency scratch codes. You use the emergency key on your mobile so that you can get the correct verification code next time you login. Emergency codes are used when you’ve lost your mobile.
Next it asks you if you want to use this for your root account? Me being root users, I’ve chosen Yes.

Do you want me to update your "/root/.google_authenticator" file (y/n) y

Next up, it asks you if you want to disallow multiple uses of the same verification code. Unless you have a good reason not to, choose Yes.

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

Next part is time based login. From the point of getting the code on your mobile to typing in to your login prompt, 30 seconds should be more than enough. If you’r time sync is bad on your system or you’ve giving the code to someone over phone or you are a VERY slow keyboard warrior, I see no reason to change it. Select Yes here.

By default, tokens are good for 30 seconds and 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 1:30min to about 4min. Do you want to do so (y/n) y

Last up, well, of course we want to enable rate-limiting, by enabling this, you ensure that only 3 login attempts every 30s can be made.

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

This finishes your initial setup for Google Authenticator PAM module. Now we need to configure PAM and SSH to actually use this technique. This is really awesome.

6 - Configure google-authenticator PAM module for the first time - blackMORE Ops

Note: Leave this terminal window open (DO NOT CLOSE). We need the codes for next steps.

Step 5: Configure SSH to use Google Authenticator PAM Module

Open your PAM configuration file /etc/pam.d/sshd

root@kali:~# vi /etc/pam.d/sshd

and add the following line:

auth       required

7 - Configure SSHD PAM to use Google Authenticator PAM Module - blackMORE Ops

Next up, open your SSH configuration file /etc/ssh/sshd_config

root@kali:~# vi /etc/ssh/sshd_config

and modify the line containing ChallengeResponseAuthentication no:

ChallengeResponseAuthentication no
(change it to)
ChallengeResponseAuthentication yes

8 - Configure sshd_config PAM to use Google Authenticator PAM Module - blackMORE Ops

To have these changes take effect, restart SSH server:

service ssh restart
service sshd restart
/etc/init.d/ssh restart
/etc/init.d/sshd restart

Why 4 commands? Depending on your Linux distribution, some refers SSH Daemon as SSHD, some as SSH, some got service module installed, some requires you to go into /etc/init.d folder and restart SSH service manually.

Step 6: Configure your SmartPhone for Google Authenticator App

Like I said before, Google Authenticator can be used in the following smartphones:

  1. Android:
  2. iOS:
  3. Blackberry:

More detailed per device install instructions can be found on this page:

Assuming you managed to install the App properly, Launch your Google Authenticator app in your SmartPhone.

From Menu select Set up account

9 - Configure SMARTPhone to use Google Authenticator - blackMORE Ops

Step 6.1: Google Authenticator Setup Account

Remember the secret key you got when you initialized Google-Authenticator PAM module on your computer? I hope you still got that window open. Select Enter provided key.

10 - Select Enter provided key on SMARTPhone to use Google Authenticator - blackMORE Ops

Next window you give it a name (something you can remember or relates to your workstation .. i.e. Home Workstation or My SuperAwesome LinuxBox … I’m going to use blackMORE Ops as the name.

Type in your Secret Key on the next field and click on Add button.

11 - Manually enter name and secret key on SMARTPhone to use Google Authenticator - blackMORE Ops

Once it’s added it will generate a one time verification code (pin number) that will keep changing every 30 seconds.

Step 7: Login to your computer via SSH

Because I am doing all these in the same computer I will just login to localhost (IP: If you got 2 or more machines or VirtualBox/VMWare machines then you can try to login from a different one. One thing to note, you MUST have SSH server running.

In case you don’t have SSH server running, just follow this guide to install openSSH server.

So we type in the following command: (this is where you need to find out your SSH server’s IP address, I’ve shown using localhost or IP but this can be anything from an IP, FQDN or Domain name.)

root@kali:~# ssh

and immediately you see a prompt asking for Verification code. This is your Google Authenticator code that you get from your Google Authenticator Mobile App.

12 - Verification Key on SMARTPhone to use Google Authenticator - blackMORE Ops

Type in the numbers from your SmartPhones Google Authenticator App and then it will prompt your for your password. Type in your password to login now.

13 - Securely SSH and enter Google Authenticator Verification Key and password to login to SSH - blackMORE Ops

If you failed to type in the Verification code within 30 seconds, you have to try the next code shown on your SmartPhones Google Authenticator App. Awesome? Wouldn’t you agree?

Alternatives to Google Authenticator SmartPhone App:

In case you don’t own a SmartPhone or don’t want to use any, you can use the following add-on on your FireFox or IceWeasel browser:

FireFox/IceWeasel App: GAuth Authenticator

15 - Secure SSH with two factor authentication using Google Authenticator from FireFox- blackMORE Ops

Interesting Fact:


Got a response from the dev behind the Google Authenticator add-on for Chrome, Gerard Braad, who explained that Google have taken it down but gave no explanation as to why even after being asked several times.

The Firefox version is still available though and work great. Hopefully he may look into the issue with the Chrome version and re-submit.

Here is the FF version for those wishing to use it:


How about that?

[ Source:!topic/chrome/P9rTLaeyHjg ]


Securing SSH with two factor authentication using Google Authenticator is possibly the best security model you can out there for free. You can always restrict SSH by IP, change port, rate-limit and do all sorts of crazy stuffs. But those who wants to open SSH to the outside world and implement all these extra security models (i.e. Brute-force detection etc.) have to constantly worry about the fact that who is trying is and what you’ve missed while securing your system. Securing SSH with two factor authentication using Google Authenticator possibly relieves you from that worry and you stop getting emails in the middle of the night saying someone tried to login via SSH X amount of times. But there’s always other ways to ensure your connection remains secure. VPN is considered to be the best solution to encrypt data. Learn how to setup VPN here.

Let me know you thoughts and if you’ve found this useful. Thanks for reading and being on my website. Please share. This would be best for System Administrators on any Linux systems.

Check Also

Whispers: A Powerful Static Code Analysis Tool for Credential Detection

“My little birds are everywhere, even in the North, they whisper to me the strangest …

Nyxt The Hacker's Browser Unleashing Power and Flexibility

Nyxt: Hacker’s Dream Browser

In the ever-evolving digital landscape, the demand for specialized tools and platforms has grown exponentially. …


  1. Incredibly useful. Thanks!

  2. Very useful but… after following the steps, restarting SSH, I still don’t get asked for the verification code. Any ideas? Also, does the .google_authenticator file need to be owned by my user or root? Thanks!

    • Hi Arnaud,
      You possibly missed a step from 3,4,5. Double check please. This worked everytime for everyuser in Debian and Kali alike.
      No, nothing for you to do in regards to file permissions. Also if you open a terminal is your own desktop, it doesn’t use SSH, it uses a local terminal. You must ssh@ to test which means you also need to setup SSH server. Easy though. All included in the guide.
      Good Luck,

    • I had to copy /usr/lib/security to /usr/lib64/security then it worked.

  3. “he/she has to register his/her phone number with Google” – it’s all part of Google secret plan. Go ahead, give Google your phone number, you will no longer need to worry about call recordings.

    • Hi Jason,
      If you’re using Android phone then you’re already exposed. Aren’t we all in some way exposed to Google? Sad but true! Btw Google Authenticator doesn’t call home. Try using it in Aeroplane mode or without a Sim. Still works.

    • You do not need to add a phone number. The secret key is generated by yourself. Thus it might be more secure, that buying an RSA token, where the selling company keeps your secret keys and thus your identity.
      I prefer hardware tokens that can be seeded like the Yubikey, the eToken NG or eToken PASS. Then you know, that your buggy computer or smartphone will not loose the secret key and you know, that you are the only owner of the key.
      So this is a legit scenario, that in fact increases your securty. Nicely and detailed written!

      By the way: If you like to authenticate with many different users or different authentication device types, you need a complete backend like privacyidea (see which makes the setup slightly more complicated – and more flexible.

      Again, thanks for the howto.

    • Hi Phamjame,
      I very much hope, this is not your OTP token? I managed to retrieve the secret key from the video.

      Kind regards

      • Hahaha hahaha that was gold cornelinux. I cracked reading the video description but your comment made me lmfao.

        • Yes, blame on me. It started me, that at 1:07 the “Security Key” was blanked, but the QR-code was not. So I screenshotted the qrcode, added the third rectangle that was missing in gimp and was – due to error correction – able to scan the QR code. This is when I wrote this comment.

          Hm, then continue to watch I see, that he enteres _another_ (fake) security key manually.
          Finally at 2:19 you are able to scan the complete key.

          The google authenticator is a great idea and easy to deploy. But the secret key is contained in the QR code in plain text!
          So you have to take care, when enrolling your token and not expose the QRcode to anybody.
          It is great that you can print out the qrcode and put it into the drawer for backup.
          But the same way, this is an attack vector.

          I had customers who were concerned to use the Google Authenticator internally with our backend, due to the fact that the users can enroll “copies” of the authentication device. Also a copy for my collegue, friend and wife. And this is not nice, if you want to use 2fa to determine the identity…

  4. I was trying to figure out why I wasn’t being asked for a verification code, but then realised this doesn’t seem to work with certificate login – at least with the configuration I am using.

    Is it possible to configure things so you can log in with certificate and Google Authenticator?

  5. Very nice write-up! I really appreciate it. Worked perfectly on my CentOS 6 server.

  6. Hi team

    How to disabled verification code for other user except root user because ChallengeResponseAuthentication is enable so it wont allow us to log-in from other user.

    Please advise.



  7. Hi everyone, for those who have got it to work, can anyone share their sshd_config file?
    I have followed the setps but I do not get asked for the verification code while SSHing, I see the normal password prompt, but the right password is not accepted, so I guess the PAM module is working but it’s unable to authenticate via TOTP, any help would be greatly appreciated :)

  8. Hello every1,

    I want to use that 2F OTP with Google Authenticator but there is one problem: I have a couple of shell scripts that logon via SSH. How do I manage to get them work with that?

    My first idea was get a code generator app that is configured to generate matching for logging in, but how do I give/insert/transmit them to the target system?

    Thanks for helpful answers.

    • Hello Chris,
      you can run OTP auth (via PAM) and RSA Pub Key auth in parallel. I.e. if the user provides a public key, there is no need for OTP, as the PAM stack is not processed. Your process could then have an ssh key. Users might log in with OTP.

      Well, but using the sshd_config statement:

      AuthenticationMethods publickey,password

      you could even required both, SSH key AND OTP as demonstrated here:

      Kind regards

      • Thanks for your quick answer and marry Christmas btw. :)

        So it’s not possible to logging via script to an user that is secured via Google Authenticator?

        • Yes it is possible.
          You can calculate the TOTP or HOTP value. But i see no benifit in doing so. In my opinion it is less secure than using ssh keys – as far as the script is concerned.

          The script needs to contain/or have access to the secret key. It needs to implemet TOTP or HOTP. And you have to play around with “expect”. Thats it.

          Kind regards and merry Christmas

          • Of course there needs to be an application that generates codes and the script needs to have access to it.

            But how do I manage to give that code to the target machine?

            To be honest I just want to maintain one authentication method and since my smartwatch has a Google Authenticator App I would prefer this besides the password.

          • Chris, if you intend on using OTP, you need to take a look at “expect”. This tool waits for certain text (lile “password: “) and writes corresponding text to stdin like “yourPasswordOTP”. At the moment I do not know, if it works fine with the ssh client. But this is the tool you need to use in suche cases.
            (But I would definitively go for ssh keys)

          • This comment section just got more interesting than the actual post.
            @Chris, I tend to agree with using SSH keys for scripts. Add IP white-listing and it’s pretty secured.

  9. And FTP?


    How the verify the sync is happens between my mobile and linux server ?

  11. Really appreciated. Good work!!

Leave your solution or comment to help others.

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

Discover more from blackMORE Ops

Subscribe now to keep reading and get access to the full archive.

Continue reading

Privacy Policy on Cookies Usage

Some services used in this site uses cookies to tailor user experience or to show ads.