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
Step by step guide
1
# Step 1: Install Google Authenticator2
apt install libpam-google-authenticator -y3
4
# Step 2: Generate your TOTP secret5
# 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.6
# Important: Store the generated backup codes somewhere secure - use your printer!7
# Recommended answers during the setup:8
# Do you want authentication tokens to be time-based (y/n) y9
# Do you want me to update your "~/.google_authenticator" file? (y/n) y10
# Do you want to disallow multiple uses of the same authentication token? (y/n) y11
# Do you want to increase the token time-skew window? (y/n) n12
# Do you want to enable rate-limiting? (y/n) y13
google-authenticator14
15
# Step 3: Back up your SSH configuration before making changes16
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak17
18
# Step 4: Configure SSH19
nano /etc/ssh/sshd_config20
# KbdInteractiveAuthentication yes # edit no to yes21
# ChallengeResponseAuthentication yes # add this to the end of the file22
# Explanation 23
# 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).24
# 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.25
26
# Step 5: Restart SSH27
systemctl restart ssh28
29
# Step 6: Back up your PAM configuration30
cp /etc/pam.d/sshd /etc/pam.d/sshd.bak31
32
# Step 7: Edit your PAM configuration33
nano /etc/pam.d/sshd34
# Add to the very to of the file: 35
## Custom: For MFA36
# auth required pam_google_authenticator.so 37
# This tells PAM to require a valid TOTP code during SSH authentication.38
39
# Step 8: Test the configuration40
Do not close your existing SSH session yet. Only close the original session after you have confirmed that MFA works correctly.41
42
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. 