Home Secure Shell (SSH) How To Setup Multi-Factor Authentication For SSH In Linux

How To Setup Multi-Factor Authentication For SSH In Linux

Configure Two-Factor Authentication For SSH On Linux

By Karthick
Published: Last Updated on 4.2k views

In this guide, we are going to learn what is Multi-Factor authentication and its importance and finally how to setup Multi-Factor authentication for SSH in Linux using Google Authenticator app.

Introduction

Security is a serious business. The number of compromises is significantly growing day by day and it is estimated that by 2025 cybercrime will cause companies 10.5 trillion USD.

It is important that a strong layer of security be implemented across all layers of the technology stack. In this article, we are going to see one such security implementation for ssh using multi-factor authentication.

SSH, stands for Secure Shell, is a network protocol that allows users to connect to the remote machines (servers) and access resources.

The ssh protocol implements two types of security namely Password-based authentication, and Key-based authentication.

Key-based (public -> private) authentication is considered more secure compared to password-based authentication and most SSH hardening instructions recommended disabling password-based authentication and enabling only key-based authentication.

Irrespective of what authentication mechanism you choose, you can make ssh more secure by implementing a multi-factor authentication setup.

What Is Multi-Factor Authentication?

Mutli-factor authentication (shortly MFA) is a secure process of authentication which requires more than one authentication technique chosen from independent categories of credentials.

Multi-Factor Authentication is also sometimes called as "Two-factor authentication (2FA)".

There are two factors involved in validating who you say you are. The first factor will be the password that is created when your user account is created.

The second factor will be any application that generates OTP or any protocol that sends you text messages or make a call to your device.

Depending upon how the application is implemented the way you authenticate vary. Some common tools you use for MFA are:

  • Application installed on the mobile device that generates tokens.
  • An external device like Yubikey.
  • Fingerprint.
  • Facial recognition.
  • Text Message or call-in based OTP password.

To enable multi-factor authentication for ssh we will be using "Google Authenticator" app which uses the OATH-TOTP protocol. There are other alternative tools like Twilio Authy or FreeOTP which you can install and try out.

We will start with installing the Google Authenticator app on both the server and mobile device and try to enable MFA and validate.

Install Google Authenticator

First Install the Google Authenticator app on your Android or IOS devices through the playstore/Itunes.

Google Authenticator App
Google Authenticator App

Now, install Google Authenticator app on your Linux system.

Depending upon your distribution, run the following installation commands.

In Ubuntu and its derivative distributions run the following command.

$ sudo apt install libpam-google-authenticator

In RHEL based distributions run the following command.

$ sudo dnf install google-authenticator -y

For Arch based distribution run the following command.

$ sudo pacman -S libpam-google-authenticator

Generate Initial Token For A User

As the first step in setting up MFA, you have to run the following command from your terminal. This will take care of the initial setup by generating the TOTP key. This key is for the user who is running the command and is not applicable to all users in the system.

$ google-authenticator

There are some sequence of steps where you will be prompted with the (y/n) option.

STEP 1 - It will prompt you to choose time-based authentication tokens. Time-based authentication tokens will generate a new code every 30 seconds. Press "y" to continue.

Run Google Authenticator Command
Run Google Authenticator Command

STEP 2 - Secret token will be generated along with a QR code. Open the Google Authenticator mobile app and scan the QR code or manually type the secret key to register the device. Once it is done, now the app will start generating tokens every 30 seconds.

Secret Keys And Verification Codes
Secret Keys And Verification Codes

STEP 3 - In this step, it will prompt you to update the .google_authenticator file under your home directory. All the secret keys, verification code, emergency scratch codes are saved in this file. Press "y" to continue.

Update google_authenticator File
Update google_authenticator File

STEP 4 - Choosing "y" in this step will expire the token immediately once you have used it to authenticate. In this case, even if some hackers get your token, it will be expired.

Disallow multiple uses of same authentication
Disallow multiple uses of same authentication

STEP 5 - This step decides how many tokens will be allowed and the time frame. When I choose "n", it will allow for 3 tokens in a 90 seconds window. If I press "y", it will allow 17 tokens in a 240 seconds time window.

Number of Tokens
Number of Tokens

STEP 6 - This step will ask you to enable rate-limiting. Rate limiting allows an attacker to try only 3 login attempts every 30 seconds. If the tokens are wrong then they have to wait for N time to try again.

Rate-Limiting
Rate-Limiting

We have completed the first step. Open the file ~/.google_authenticator and you can find all the settings and secret codes we made through all these steps.

$ cat ~/.google_authenticator
View google_authenticator Settings
View google_authenticator Settings

You can also pass arguments to the google-authenticator command which will create the keys and other settings without going through this sequence of steps.

$ google-authenticator -q -t -d -f -r 3 -R 30 -w 3

Refer the Google authenticator help section to find what those arguments will do.

$ google-authenticator –-help
Display google-authenticator Help Section
Display google-authenticator Help Section

Configure SSH For Multi-Factor Authentication

We have to make some configuration changes to openSSH so we can start using MFA.

Note:

  • As a best practice, always backup your configuration files before making any changes. If anything is messed up the changes can be reverted.
  • Since you are making changes to SSH configuration files, make sure you have a session opened separately, so you are not going to be locked out of yourself by accidentally.

Run the following commands to back up the SSH config files.

$ sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup
$ sudo cp /etc/pam.d/sshd /etc/pam.d/sshd.backup

First, enable SSH to use MFA by setting ChallengeResponseAuthentication option to "yes".

Configure SSH to use MFA
Configure SSH to use MFA

Next, edit the /etc/pam.d/sshd file:

$ sudo vi /etc/pam.d/sshd

And add the following lines to the bottom of the file.

auth required pam_google_authenticator.so nullok
auth required pam_permit.so
Edit sshd Pam Configuration File
Edit sshd Pam Configuration File

If you wish to make MFA mandatory for all users, then remove the word "nullok".

Restart the ssh service to make the changes effective.

$ sudo systemctl restart sshd

Test Two Factor Authentication

It’s time to test if the changes we made are effective.

Connect to the server via SSH and you will be asked for a password as the first factor followed by a verification code as the second-factor authentication as shown in the below image.

$ ssh username@hostname/IPaddress
Test Two Factor Authentication
Test Two Factor Authentication

Once you entered the SSH password and the verification code, you will able to login.

Did you remember that we have not enabled MFA as mandatory for all users? Let's test it and see if I am able to connect with another user where I do not have generated and set up tokens.

I have a testuser and I am able to connect successfully without prompting for verification code.

Connect Using Alternate User
Connect Using Alternate User

See? I can able to login without the verification code as well.

Multi-Factor Authentication For Key Based Authentication

If you have set up a key-based authentication, then you will not be promoted for the password or verification codes. Why?

Because, by default ssh uses public-key authentication first and if there is a key found then it authenticates using that. In case the key is not found, it will use password-based authentication.

You can use verbose mode to check this.

$ ssh -v username@hostname/IPaddress ## With verbose
SSH With Verbose Mode
SSH With Verbose Mode

Add the following line to the bottom /etc/ssh/sshd_config file:

AuthenticationMethods publickey,password publickey,keyboard-interactive

Next open /etc/pam.d/sshd and comment out the following line.

Common Auth
Common Auth

If you are not commenting out "@include common-auth", then it will enable more than two factors to authenticate. It will first authenticate using keys followed by password and tokens. All I need is a key and token for my authentication, so I am disabling it.

Three-Factor Authentication
Three-Factor Authentication

Restart the sshd service and test out if the changes work fine.

$ sudo systemctl restart sshd

Now If I try to connect, it uses public-key as the first factor and verification code as the second factor to authenticate.

Key And Verification Code
Key And Verification Code

Recovery Steps

There may be scenarios where you may lose or change your mobile device. In that case, you have to reinstall the google-authenticator application and register the secret key to start generating tokens.

If you are locked out of the system, then you have to reach out to your system administrator to provide you with new secret keys to register and use it. But there is an alternative approach where you can log in and generate keys on your own.

Remember the codes that are generated during the initial step? You can use the emergency scratch code as a token to log in. Each scratch code can be used only once. Save it someplace safe so it can be used when needed the most.

The codes are saved in ~/.google_authenticator file.

$ cat ~/.google_authenticator
Scratch Codes
Scratch Codes

You can now regenerate your own keys again by running the following command.

$ google-authenticator

Conclusion

In this article, I have shown you how to install google authenticator and enable Multi-factor Authentication for SSH with different configurations.

As an administrator, you can also write bash scripts to automate the process of generating the secret keys and share it with the user. You should also harden the ssh before setting up MFA, so your system is more secure. We are planning to cover them in separate articles. Stay tuned!

You May Also Like

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

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

This website uses cookies to improve your experience. By using this site, we will assume that you're OK with it. Accept Read More