14th January 2016

SSH: two-factor authentication

This must be the best way to strengthen the security on your ssh connection for those cases where ssh keys are not available: Using 2 factor authentication for SSH

Install Google Authenticator app in your smartphone

It is available in the Android Play Store and the iOs App Store.

It could be installed on a computer via the Oath Toolkit, but in this case it would be better using SSH keys (or none, if unsecure).

Install Google Authenticator software on the server

The source code is at https://github.com/google/google-authenticator/archive/master.zip and it can be installed for debian directly:

apt-get install libpam-google-authenticator

Execute the Google Authenticator software on the server

This authenticator must be executed using the account that will be used to login in the system; if there are multiple accounts, it must be executed once per account.


This asks several questions -all should be answered with yes-, and will display a QR code that can be loaded directly on the smartphone app, together with the secret key, verification code and emergency scratch codes.

To configure the app, load the QR on the phone, or enter alternatively the provided secret key

Configuring PAM and SSH

With sudo access:

echo -e "\nauth required pam_google_authenticator.so" >> /etc/pam.d/sshd

Edit now the file /etc/ssh/sshd_config, and replace the line with the key ChallengeResponseAuthentication to have the value yes (or add the line if not found):

ChallengeResponseAuthentication yes

Finally, restart ssh:

service ssh restart

Updating / regenerating new authentication code

Just execute again the authenticator on the server:


And load the new codes on the phone

Configuring two factor authentication for specific users

The above configuration requires all users to use two factor authentication. This can be restrained to specific users by using the Match clause in the /etc/ssh/sshd_config file:

Match User svn
     ChallengeResponseAuthentication no
Unfortunately, at least under Debian, ChallengeResponseAuthentication is not supported as a Match subqualifier.