This setup requires the Google Authenticator app to generate OTPs (One-Time Passwords).

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

Append the following:

auth required pam_google_authenticator.so nullok

The nullok option allows users to log in even if they have not set up 2FA yet.

Edit the OpenSSH server configuration:

sudo nano /etc/ssh/sshd_config

Update these options:

ChallengeResponseAuthentication yes
PasswordAuthentication no
AuthenticationMethods publickey,keyboard-interactive

Make sure you have SSH key access before setting PasswordAuthentication to no.

To enable 2FA for sudo instead (do NOT combine 2FA for SSH and sudo; use one or the other):

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

Append:

auth required pam_google_authenticator.so nullok
auth required pam_permit.so

Run the authenticator to generate a QR code for the current user:

google-authenticator

Restart the SSH service, then test your login from a separate terminal to avoid being locked out:

sudo systemctl restart sshd.service

Note: a new file ~/.google_authenticator is created during setup. It can be backed up or copied to other servers you want to access with the same token.

Once all users have set up Google Authenticator, edit /etc/pam.d/sshd and remove nullok, leaving:

auth required pam_google_authenticator.so

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

head -n 1 /home/user/.google_authenticator

If that is not possible, delete the configuration file and ensure the nullok option is enabled. The user will then be able to log in without 2FA and generate a new QR code:

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

Note: the arguments -t -d -f -r 3 -R 30 -W are optional and enable non-interactive setup.

To prompt a user to set up 2FA on their next login, create the following file in their home directory:

sudo nano /home/user/.bash_login

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 include this script in every new user’s home directory automatically, copy it to:

sudo cp .bash_login /etc/skel/.bash_login