How to protect SSH with Two-Factor Authentication

To protect your server with an two-factor authentication, you can use the Google Authenticator PAM module.

Every time you connect you have to enter the code from your smartphone.

*If you activate the google-authenticator for a normal user but not for root you can’t login with the root user directly anymore. You will need to login as the new user first, then switch to the super user with the su command to get root*

Before you do anything on your server, install the Google Authenticator application, it is available for Android, iOS and BlackBerry.

After this connect to your server make sure you’re the root user.

Install Dependencies:

~# apt-get install libpam-google-authenticator

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

Edit the Configuration Files:

~# nano /etc/pam.d/sshd

Add the following line on top of the file:

auth required pam_google_authenticator.so

then edit:

~# nano /etc/ssh/sshd_config

Find and change the following line:

ChallengeResponseAuthentication yes

You can activate the google-authenticator for the root user or any other user. Switch to the user who should use the two-factor authentication and type in:

~# google-authenticator

You will be prompted to answer a few questions; answer the first two questions with yes (y):

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

You can answer the next questions according to your requirements.

You can use the Google Authenticator app to scan the qr-code, or add the account using the secret key and the verification code. Do not forget to print out the emergency scratch codes and store them in a safe place!

Now switch back to root and restart the SSH server. If you added the two-factor authentication for the root user you can skip the next step.

~$ su root

Finally restart the SSH server:

~# /etc/init.d/ssh restart

BOOM! You should now have a SSH server with an two-factor authentication!

Activate the Two-Factor Authentication For a User:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s