This setup will require the Google Authenticator app to create the OTP (One-Time-Password).

sudo apt install libpam-google-authenticator -y
sudo nano /etc/pam.d/sshd

Append the configuration:

auth required pam_google_authenticator.so nullok

The last piece of the configuration above (nullok) allows users to log in if they did not set up the 2FA yet.

Edit the OpenSSH-Server configuration:

sudo nano /etc/ssh/sshd_config

And change these options:

ChallengeResponseAuthentication yes
PasswordAuthentication no
AuthenticationMethods publickey,keyboard-interactive

Make sure that you have access with an SSH-Key before setting the password option to no.

Enable 2FA for sudo (do NOT combine the 2FA for SSH + SUDO, use one or other):

sudo nano /etc/pam.d/common-auth

Append:

auth required pam_google_authenticator.so nullok
auth required pam_permit.so

Now, execute the authenticator to generate the QR-Code for the current user.

google-authenticator

Now, restart the SSH service, then try to log in using another terminal to prevent being locked out.

sudo systemctl restart sshd.service

Note: a new file ~/.google_authenticator was created. It can be backed up or even copied to other servers that you want to have access to with the same token.

After all the users have set up their Google-Authenticator, remember to edit /etc/pam.d/sshd and remove the nullok, leaving the configuration as follows:

auth required pam_google_authenticator.so

To recover access to a user account, read the first line of the configuration file as root and type it in the user’s Google Authenticator app:

head -n 1 /home/user/.google_authenticator

If it is not possible, just delete the configuration file and make sure the nullok option is still enabled. In this case, the user will be able to log in without the 2FA and create a new QR code for the 2FA:

google-authenticator -t -d -f -r 3 -R 30 -W

Note: all the additional arguments -t -d -f -r 3 -R 30 -W are optional. They can be used to set it up in a non-interactive mode.

To force a user to set up its 2FA on the log on, create the following file in the user’s home directory:

sudo nano /home/user/.bash_login

Then, paste the following content:

#!/bin/bash
FILE=~/.google_authenticator
if [ ! -f "$FILE" ]; then
echo ""
echo "|-------------------------------------------------------------------------------------------------|"
echo "| Download the Google Authenticator app on your smartphone and scan the following QR code: |"
echo "|-------------------------------------------------------------------------------------------------|"
echo ""
google-authenticator -t -d -f -r 3 -R 30 -W
fi

To have this script placed in the home directory of every new user upon creation copy it to the following directory:

sudo cp .bash_login /etc/skel/.bash_login