Configure SSH to use Two factor authentication Print

  • ssh
  • 0

Multi-factor authentication is a method of confirming your identity using at least two different ways of authentication. The most common and easiest to implement example of two-factor authentication uses a combination of passphrase (a complex password, often made of several words) and one-time-passcode generated by a special mobile app.

We will use the Google Authenticator app available for Android (in the Play Store) and iOS (in iTunes) to generate authentication codes.

Step 1. Installing the Google Authenticator

Ubuntu / Debian

apt install libpam-google-authenticator

RHEL / AlmaLinux

dnf install epel-release
dnf install google-authenticator

ArchLinux

pacman -S libpam-google-authenticator

openSUSE / SLES

zypper install google-authenticator-libpam

Step 2. Configuration of the Google Authenticator

After the PAM module has been installed, it can be initialized and configured as shown below.

Starting the Google Authenticator:

google-authenticator

It will ask you a series of questions, here is a recommended configuration:

  • Make tokens “time-base””: yes
  • Update the .google_authenticator file: yes
  • Disallow multiple uses: yes
  • Increase the original generation time limit: no
  • Enable rate-limiting: yes

You may have noticed the giant QR code that appeared during the process, underneath are your emergency scratch codes to be used if you don’t have access to your phone: write them down on paper and keep them in a safe place.

Step 3. Integration into the SSH logon

The Google Authenticator PAM module is configured ready, now services like the SSH daemon can be customized to allow 2-factor authentication over it.

Adjustments in /etc/pam.d/sshd
Here the time @include common-auth must be commented out with a # at the beginning of the line. Then the line auth required pam_google_authenticator.so is inserted.

Adaptations in /etc/ssh/sshd_config
In the configuration file the ChallengeResponseAuthentication can now be set to yes.

Ubuntu 22.04 and newer versions need to adjust this flag instead:

KbdInteractiveAuthentication yes

Also the entries UsePAM and AuthenticationMethods should be checked. The entry UsePAM should be set to yes and AuthenticationMethods should look like this:

AuthenticationMethods publickey,keyboard-interactive

Step 4. Restart the SSH service

RHEL/Almalinux:

systemctl restart sshd

Debian/Ubuntu:

systemctl restart ssh

After that the setup of the Two Factor Authentication is complete.


Was this answer helpful?

« Back