Enable TOTP 2FA for SSH Access

Configure TOTP two-factor authentication for SSH logins using PAM and Google Authenticator. Secure your servers with time-based one-time passwords alongside SSH keys.

Platform Integration

Detailed Explanation

Adding TOTP to SSH Authentication

Securing SSH access with TOTP adds a second factor beyond passwords or SSH keys. The most common approach on Linux uses Google Authenticator PAM module (libpam-google-authenticator), which integrates TOTP verification into the SSH login process.

Installation

On Debian/Ubuntu:

sudo apt-get install libpam-google-authenticator

On RHEL/CentOS:

sudo yum install google-authenticator

Per-User Setup

Each user runs the setup command:

google-authenticator

This interactive wizard:

  1. Generates a new TOTP secret
  2. Displays a QR code in the terminal (ASCII art)
  3. Provides emergency backup codes
  4. Asks configuration questions (time-based, window size, rate limiting)
  5. Writes ~/.google_authenticator with the secret and settings

PAM Configuration

Edit /etc/pam.d/sshd to add the authenticator module:

auth required pam_google_authenticator.so

Place this line after @include common-auth for password + TOTP, or configure it alongside SSH key authentication.

SSH Server Configuration

Edit /etc/ssh/sshd_config:

ChallengeResponseAuthentication yes
UsePAM yes
AuthenticationMethods publickey,keyboard-interactive

The AuthenticationMethods line requires both an SSH key and a TOTP code. Restart sshd after changes:

sudo systemctl restart sshd

Authentication Flow

After configuration, SSH login proceeds as:

  1. Client presents SSH public key (verified against authorized_keys)
  2. Server prompts for verification code
  3. User enters the current TOTP code from their authenticator app
  4. Both factors verified → access granted

Important Considerations

  • Test in a separate session before logging out — misconfiguration can lock you out
  • Keep a root console open during setup for emergency access
  • Backup the secret file (~/.google_authenticator) alongside your SSH keys
  • Service accounts may need exemption from TOTP (use Match User in sshd_config)
  • Automated scripts that use SSH will need alternative authentication paths

Use Case

System administrators securing production servers need TOTP as a second factor for SSH access, especially when compliance frameworks (SOC 2, PCI DSS, ISO 27001) require multi-factor authentication for administrative access. This guide is essential when hardening server access controls, setting up bastion hosts with 2FA, or responding to audit findings that recommend MFA for all SSH sessions.

Try It — TOTP Generator

Open full tool