How to Protect SSH with Google Two-Factor Authentication

Google now provides an absolute open source software to protect your SSH server. Google Authenticator PAM module known as two factor authentication  can be used to connect to the server using the code from your smartphone.

Before proceeding to securing SSH server, first you should install the Google Authenticator application on your smartphone. It’s already  available for Android, iOS and BlackBerry. After installing the app, you can connect to your VPS.

Installing Google Authenticator

 

Ubuntu’s repositories have a ready-to-install package for Google Authenticator PAM module. Just execute the command given below:

sudo apt-get install libpam-google-authenticator

This will install ‘libqrencode3’ automatically and will let you use camera of your smartphone for scanning its qr-code from the console.

 

Configuration File Changes

 

The PAM stands for “pluggable authentication module”. For using the module, two configuration files have to be updated.

vim /etc/pam.d/sshd

Update the above mentioned file with the line given below on top of the file.

auth required pam_google_authenticator.so

Now, let’s go ahead and edit the second file.

vim /etc/ssh/sshd_config

 

Search for the following line and update it.

ChallengeResponseAuthentication yes

 

Activation of Google Authenticator for a User

 

Google authenticator can be activated for root user or any other user.

Note: If you activate it for a user other than root, you will not be able to login with root user directly. First you have to login as the normal user and then switch to root using the su command.

 

Switch to the user who you want to activate the two-factor authentication and type:

google-authenticator

You will have to type in ‘yes’ for the following questions:

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

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

You may be prompted for a few more questions, which you can answer according to your requirements.

Using the Google Authenticator app, scan the qr-code or you can add the account using secret key and verification code. You may print out the emergency scratch codes and keep them handy.

You can switch back to the root user and restart the SSH server. Here we have done the two-factor authentication for the normal user. If you did for the root user, you may skip this step.

su root
/etc/init.d/ssh restart

Now, you have successfully secured the SSH server with two factor authentication.

KB Admin has written 46 articles