Home How ToHow to Set Up Two-Factor Authentication for SSH on Linux

How to Set Up Two-Factor Authentication for SSH on Linux

by Knowledge Base Linux
How to Set Up Two-Factor Authentication — How to Set Up Two-Factor Authentication for SSH on Linux

Passwords and even SSH keys can be stolen, leaked or brute-forced. Adding SSH two-factor authentication to your Linux server means an attacker needs something you have — your phone’s authenticator app — in addition to something you know. In this guide you will set up SSH two-factor authentication with the Google Authenticator PAM module, keep a safe recovery path, and combine it with key-based login for defense in depth. This article covers How to Set Up Two-Factor Authentication in detail.

How SSH Two-Factor Authentication Works – How to Set Up Two-Factor Authentication

The Google Authenticator PAM module generates time-based one-time passwords (TOTP) — the same six-digit codes used by countless services. When you log in over SSH, after your password or key is accepted, sshd asks for a verification code. The code changes every 30 seconds and is derived from a secret stored only in your home directory and your authenticator app. Because PAM is pluggable, no SSH client changes are needed: any modern OpenSSH client will display the extra prompt.

Before You Start: Safety Rules – How to Set Up Two-Factor Authentication

  • Keep your current SSH session open until everything is tested — a misconfiguration can lock you out
  • Open a second session to test in, and know how to reach the server console through your hosting panel
  • These steps complement, not replace, hardening such as installing Fail2Ban to protect SSH and generating SSH keys

Step 1: Install the Google Authenticator PAM Module

# Ubuntu / Debian
sudo apt update
sudo apt install -y libpam-google-authenticator

# RHEL / AlmaLinux / Rocky (EPEL required)
sudo dnf install -y epel-release
sudo dnf install -y google-authenticator

Step 2: Enroll Your User

Run the enrollment tool as the user who will log in (not with sudo):

google-authenticator

Answer yes to time-based tokens, scan the QR code with your authenticator app (Google Authenticator, Microsoft Authenticator, Authy or any TOTP app), then answer yes to updating the configuration file, yes to disallowing token reuse, and yes to rate limiting. Crucially, save the printed emergency scratch codes somewhere safe and offline — they are your only way in if you lose your phone.

The tool creates ~/.google_authenticator with strict permissions. Verify them:

chmod 600 ~/.google_authenticator
ls -l ~/.google_authenticator
How SSH two-factor authentication verification works step by step

Step 3: Enable SSH Two-Factor Authentication in PAM

Tell PAM to require the module for SSH logins by editing /etc/pam.d/sshd. Add this line at the end of the file:

auth required pam_google_authenticator.so

To require the code in addition to a public key (keyboard-interactive after key auth), also comment out the common-auth password stack line in the same file so users cannot bypass the second factor with a password alone:

#@include common-auth

Be careful here: editing PAM incorrectly affects all logins. Change one thing at a time and test after each change.

Step 4: Configure sshd

Edit /etc/ssh/sshd_config (or drop a file into /etc/ssh/sshd_config.d/) and set:

KbdInteractiveAuthentication yes
ChallengeResponseAuthentication yes
AuthenticationMethods publickey,keyboard-interactive

AuthenticationMethods publickey,keyboard-interactive is the key line: it forces successful public-key authentication and then the keyboard-interactive prompt where PAM asks for the TOTP code. Check the syntax and restart SSH:

sudo sshd -t
sudo systemctl restart sshd

Step 5: Test in a New Session

From a second terminal, log in verbosely and watch the prompts:

ssh -v user@your-server

You should see the key accepted first, followed by a Verification code: prompt. Enter the current six-digit code from your app. Only after this works should you close your original session.

Troubleshooting

Code always rejected: TOTP depends on accurate time on both devices. Check the server clock with timedatectl and ensure NTP synchronization is active.

No code prompt appears: the client or an old sshd_config.d drop-in is overriding KbdInteractiveAuthentication. Run sudo sshd -T | grep -i kbd to see the effective value.

Locked out: use a scratch code at the prompt, or log in through the hosting console and remove the PAM line. The official libpam documentation covers advanced options such as allowing specific networks to skip the second factor.

Managing 2FA for Teams

On shared servers, roll out SSH two-factor authentication user by user rather than all at once. Each person enrolls their own account with google-authenticator before you enforce the PAM requirement globally; anyone who has not enrolled will be unable to answer the code prompt and will be locked out. Keep one break-glass account protected by a strong key and a scratch code stored in a sealed location for genuine emergencies. PAM also supports the nullok argument — auth required pam_google_authenticator.so nullok — which lets users who have not enrolled yet log in without a code; this is useful during migration week, but remove it afterwards, because it silently disables the second factor for any account whose enrollment file goes missing. Finally, document the recovery process: a lost phone means a new enrollment, which an administrator can reset by deleting that user’s ~/.google_authenticator file from a root shell.

Conclusion

SSH two-factor authentication takes about ten minutes to configure and removes one of the most common ways servers are compromised: a single stolen credential. Combined with key-only login, Fail2Ban and a non-standard port, your SSH surface becomes dramatically harder to attack — while legitimate logins cost you only a few extra seconds.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.