1. Home
  2. Tutorials
  3. Servers
  4. Protecting SSH With Two-Factor Authentication

Protecting SSH With Two-Factor Authentication

Protecting SSH with Two Factor Authentication
Protecting SSH with Two Factor Authentication


In order to protect your SSH server using a two-factor authentication, you may use the Google Authenticator PAM module.

Every time you connect you’ll need to enter the code from your smartphone.

Note: In case you activate the google-authenticator for a regular user but not for root you won’t be able to login with the root user directly anymore. You’ll have to login as the new user first, then go back to the super user with the su command to get root.

Before we do anything on the VPS, install the Google authenticator application, it should be available for Android, iOS and BlackBerry. Install the App with the market or go into your mobile browser and enter m.google.com/authenticator. Then, connect to your VPS and change to the root user.

Step One – Install Dependencies

sudo apt-get install libpam-google-authenticator

libqrencode3 should be installed automatically and then allow you to use the camera of your phone to scan the qr-code directly from the console.

Step Two – Edit the Configuration File

In order to use the module you’ll need to modify two configuration files.

nano /etc/pam.d/sshd

Append the line shown in the following to the top of the file:

auth required pam_google_authenticator.so

Another file to modify:

nano /etc/ssh/sshd_config

Search and replace the following line:

ChallengeResponseAuthentication yes

Step Three – Activate the Two-Factor Authentication For a User

You may activate the google-authenticator for the root user or any other user. Change to the user who is going to use the two-factor authentication and enter the following:


You are going to be asked a couple of questions, answer the two questions using (y) yes:

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

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

Feel free to answer the next questions according to your own needs.

Also be sure to use the Google Authenticator app to either scan the qr-code, or add an account with the secret key and the verification code. A reminder to not forget printing out the emergency scratch codes and then storing them in a safe place.

Next, change back to root and restart the SSH server. In case you’ve added two-factor authentication for the root user you may move to the next step.

su root

Lastly, restart the SSH server.

/etc/init.d/ssh restart

That’s all, you will now have a SSH server with an two-factor authentication.

Updated on December 9, 2017

Was this article helpful?

Related Articles

Add A Comment