C.W.K.
Stream
Lesson 06 of 14 · published

Two-Factor SSH (TOTP)

~15 min · 2fa, totp, google-authenticator, pam

Level 0Pinger
0 XP0/101 lessons0/12 achievements
0/150 XP to next level150 XP to go0% complete

Adding a second factor

Even with key-only auth, a stolen private key (laptop theft, agent forwarding mishap) means an attacker can log in. Two-factor SSH requires both the key and a TOTP code from an authenticator app. Optional but a strong defense for high-value servers.

The flow

Server uses PAM's pam_google_authenticator module. User runs the setup tool, scans the QR code into their authenticator app, gets backup codes (save them!). On future SSH, after key auth, the server asks for the 6-digit verification code. With ssh-agent caching, the key part is automatic; you only type the code.

Code

Install on a Linux server·bash
# Install the PAM module
sudo apt install libpam-google-authenticator

# Run the setup tool AS YOUR USER (not root)
google-authenticator
# Answer prompts — accept defaults for time-based, disallow reuse, rate limit on
# Scan the QR code with Authy / Google Authenticator / 1Password
# SAVE THE BACKUP CODES somewhere you can find without your phone
Wire it into SSH·bash
# Edit PAM
sudo nano /etc/pam.d/sshd
# Add at the bottom:
auth required pam_google_authenticator.so

# Edit sshd_config
sudo nano /etc/ssh/sshd_config
# Set:
KbdInteractiveAuthentication yes
AuthenticationMethods publickey,keyboard-interactive

# Validate and restart
sudo sshd -t
sudo systemctl restart sshd

# Test from a NEW session
ssh user@host
# Expected: key auth (silent if agent has key), then TOTP prompt

External links

Exercise

On one server (test, not the only one), set up TOTP via the steps above. Practice the full flow: SSH from a new session, observe the prompt for verification code, type it. Then test the recovery — pretend you lost your phone, use a backup code instead. If the recovery works, you've configured 2FA correctly. If you lock yourself out, your lifeline session can fix it.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.