Docs / Security / Setting Up Two-Factor Authentication for SSH

Setting Up Two-Factor Authentication for SSH

By Admin · Feb 25, 2026 · Updated Apr 23, 2026 · 170 views · 1 min read

Overview

Two-factor authentication (2FA) adds a second layer of security to SSH by requiring a time-based one-time password (TOTP) in addition to your SSH key or password.

Install Google Authenticator PAM

sudo apt install -y libpam-google-authenticator

Configure Per User

As the user who will use 2FA:

google-authenticator

Answer the prompts:

  • Time-based tokens? Yes
  • Update the .google_authenticator file? Yes
  • Disallow multiple uses? Yes
  • Rate limiting? Yes

Scan the QR code with your authenticator app (Google Authenticator, Authy, or any TOTP app).

Configure PAM

Edit /etc/pam.d/sshd:

# Add at the end
auth required pam_google_authenticator.so

Configure SSHD

Edit /etc/ssh/sshd_config:

ChallengeResponseAuthentication yes
AuthenticationMethods publickey,keyboard-interactive

This requires both an SSH key AND a TOTP code.

Restart SSH

sudo systemctl restart sshd

Testing

ssh -o PreferredAuthentications=publickey,keyboard-interactive user@server
# You will be prompted for your verification code after key auth

Backup Codes

During setup, you received emergency scratch codes. Store these securely — they can be used if you lose your authenticator device. Each backup code can only be used once.

Important Notes

  • Keep an active SSH session open while configuring — if something goes wrong, you can fix it
  • Test from a new terminal before closing your current session
  • Store backup codes in a password manager

Was this article helpful?