Two factor linux authentication using Google Authenticator

First thing you need is to install google authenticator package in Debian:

apt-get install libpam-google-authenticator

Open a shell for the user you want to use two-factor authentication and run command called “google-authenticator”


You are presented with several questions to which I have answered “y” (yes) on all.

Save your secret key, verification code and emergency scratch codes to a secure location in case you need them.

On your android phone install Google Authenticator and go to “Set Up account” choose “Scan a barcode” and take a photo of your provided image from google-authenticator or second option is to “Enter provided key” where you enter your provided secret key.

There are several configuration steps to do before your SSH will use two-factor authentication.

Edit your /etc/pam.d/sshd configuration file and add bellow line:

@include common-auth

these two lines:

auth [success=1 default=ignore] accessfile=/etc/security/access-local.conf
auth required nullok

This will ask for google authenticator code after you type in your username and password. If you put these two lines above then authenticator code would be asked first before password, but this is not a good security practice since it will confirm that this user exists on the system for brute force attacks.

First line in PAM means that on success it should skip 1 next authentication provider (in our case two-factor auth), and on failure pretend if it did not happen.

In the configuration file /etc/security/access-local.conf you can configure networks for which two-factor authentication will not be enabled. This is useful if you want only connections from the outside network to be asked to type in google authentication code, but internal connections will work without it.

So your file /etc/security/access-local.conf should look like this:

# Skip two-factor auth for local network
+ : ALL :
- : ALL : ALL

The “nullok” in the second line option instructs PAM whenever no config for two-factor authentication is found, it should just ignore it.

Edit your /etc/ssh/sshd_config conf and change value:

ChallengeResponseAuthentication no


ChallengeResponseAuthentication yes

After this just restart your ssh but remember to keep your existing connection just in case you made a mistake in the configuration.

Your existing SSH connections that use authentication keys will work as before without changes.

You can move authenticator configuration files out of user home directory to another location for example to users .ssh folder and edit /etc/pam.d/sshd to point to a new file location easily with:

auth required nullok secret=/home/${USER}/.ssh/.google_authenticator

There is no harm in skipping this step if you do not need it.

Leave a Reply

Your email address will not be published. Required fields are marked *

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