Configure MFA (TOTP)

Deescription

In this guide, you will learn how to secure SSH access to your VPS with multi-factor authentication (MFA) using TOTP and the Google Authenticator PAM module.

We are using the Linux operating system Ubuntu 24.04.

What you’ll learn
  • Install the Google Authenticator PAM module.
  • Generate a TOTP secret and QR code.
  • Configure SSH to support interactive MFA authentication.
  • Configure PAM to require a TOTP code.
  • Restart SSH and test the configuration.
Step by step guide
Bash
# Step 1: Install Google Authenticator
apt install libpam-google-authenticator -y

# Step 2: Generate your TOTP secret
# The following command will generate a TOTP secret and display a QR code and backup codes. Scan the QR code with an authenticator app such as Google Authenticator, Aegis, or another TOTP-compatible app.
# Important: Store the generated backup codes somewhere secure - use your printer!
# Recommended answers during the setup:
# Do you want authentication tokens to be time-based (y/n) y
# Do you want me to update your "~/.google_authenticator" file? (y/n) y
# Do you want to disallow multiple uses of the same authentication token? (y/n) y
# Do you want to increase the token time-skew window? (y/n) n
# Do you want to enable rate-limiting? (y/n) y
google-authenticator

# Step 3: Back up your SSH configuration before making changes
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak

# Step 4: Configure SSH
nano /etc/ssh/sshd_config
# KbdInteractiveAuthentication yes # edit no to yes
# ChallengeResponseAuthentication yes # add this to the end of the file
# Explanation 
# KbdInteractiveAuthentication – When enabled in SSH, it allows the server to engage in the 2FA interactive process. For example, after entering your password (the first factor), the server might prompt you for a code from your 2FA app (the second factor).
# ChallengeResponseAuthentication – When enabled, the SSH server can use challenge-response methods for authentication. This includes methods like keyboard-interactive authentication, where the user is prompted to enter information in response to a challenge. In other words, in that case, it allows the SSH server to prompt the user to enter a code generated by a 2FA app.

# Step 5: Restart SSH
systemctl restart ssh

# Step 6: Back up your PAM configuration
cp /etc/pam.d/sshd /etc/pam.d/sshd.bak

# Step 7: Edit your PAM configuration
nano /etc/pam.d/sshd
# Add to the very to of the file: 
## Custom: For MFA
# auth required pam_google_authenticator.so 
# This tells PAM to require a valid TOTP code during SSH authentication.

# Step 8: Test the configuration
Do not close your existing SSH session yet. Only close the original session after you have confirmed that MFA works correctly.

Open a second terminal and establish a new SSH connection to your VPS. You should now be prompted for your TOTP code and the SSH credentials. 
Next steps