Linux VPS7 min read•Last updated: •By SkyRain Cloud Team

How to Add Two-Factor Authentication to SSH on a Linux Server

SSH keys already make a Linux server far harder to break into than passwords do. But a key is still a single factor: if a laptop is stolen or a private key leaks from a backup, whoever holds it can log in. Adding two-factor authentication to SSH means a login also needs a one-time code from your phone, so a stolen key on its own is not enough.

This guide sets up time-based one-time passwords (TOTP) for SSH on Ubuntu or Debian, the same six-digit codes used by Google Authenticator, Microsoft Authenticator and similar apps. It combines them with SSH keys, shows how to test without locking yourself out, and covers hardware security keys as an alternative.

Quick answer

Install libpam-google-authenticator, run google-authenticator as your user and scan the QR code into an authenticator app. Add auth required pam_google_authenticator.so to /etc/pam.d/sshd, set KbdInteractiveAuthentication yes and AuthenticationMethods publickey,keyboard-interactive in the SSH server configuration, then restart SSH while keeping your current session open. Every login then needs your SSH key plus a six-digit code.

How SSH two-factor authentication works

OpenSSH can require several authentication methods in sequence. In this setup:

  1. Something you have: your SSH private key, checked first.
  2. Something else you have: your phone, which generates a new six-digit code every 30 seconds from a shared secret.

The code check is handled by a PAM module (Linux's pluggable authentication system). OpenSSH asks PAM through the keyboard-interactive method, which is why that method must be enabled. Because codes are based on time, the server's clock must be accurate; check with timedatectl that System clock synchronized says yes.

Two-factor authentication – SkyRain Cloud servers in India

Step-by-step setup on Ubuntu or Debian

1. Keep a safety session open

Open two SSH sessions to the server before you start. Make all changes in one and keep the other untouched until you have confirmed a fresh login works. If you get it wrong, the spare session (or your provider's web console) is how you fix it.

2. Install the PAM module

sudo apt update
sudo apt install libpam-google-authenticator

3. Create your secret

Run this as the user who logs in over SSH (not with sudo):

google-authenticator

Answer yes to time-based tokens. A QR code appears; scan it with your authenticator app. The tool also prints emergency scratch codes: store them in a password manager, because they are your way in if you lose your phone. For the remaining questions, sensible answers are yes to updating the file, yes to disallowing reuse, no to increasing the time window, and yes to rate limiting.

4. Tell PAM to ask for the code

Edit /etc/pam.d/sshd. Add this line at the end:

auth required pam_google_authenticator.so

If you log in with keys (recommended), also comment out the line @include common-auth near the top. Otherwise PAM asks for your Linux password as well as the code.

5. Configure the SSH server

Create /etc/ssh/sshd_config.d/60-2fa.conf:

KbdInteractiveAuthentication yes
UsePAM yes
AuthenticationMethods publickey,keyboard-interactive

On older releases that do not recognise KbdInteractiveAuthentication, use ChallengeResponseAuthentication yes instead. Check the configuration, then restart SSH:

sudo sshd -t
sudo systemctl restart ssh

The options are documented in the sshd_config manual.

6. Test from a new terminal

ssh user@203.0.113.25

You should be asked for a Verification code after your key is accepted. Only when this works should you close the safety session.

Rolling out two-factor authentication to a team

  • Each person runs google-authenticator for their own account, so secrets are never shared.
  • Use nullok during rollout (auth required pam_google_authenticator.so nullok) to let users without a secret log in while they set one up. Remove it once everyone is enrolled.
  • Exempt automation carefully. Backup jobs and deployment tools that connect over SSH cannot type codes. Give them their own key-only account restricted with Match User to a specific command or IP address, rather than weakening the rule for everyone.
  • Document recovery. Decide who can reset a user's secret (delete their ~/.google_authenticator file) and how identity is checked first.

Two-factor options for SSH compared

OptionHow it worksProsCons
Key + TOTP codeSSH key, then six-digit code from an appFree, works with any phoneTyping codes; codes can be phished in theory
Hardware security key (FIDO2)ssh-keygen -t ed25519-sk; touch the key to log inPhishing-resistant, fastRequires buying keys; needs OpenSSH 8.2 or later
VPN with MFA in front of SSHSSH reachable only through a VPN that enforces MFAProtects all services at onceMore moving parts
Key only (no second factor)SSH key aloneSimpleA stolen key is enough

Mistakes that cause lockouts

  • Closing every session before testing. Always test from a new terminal first.
  • Wrong server time. Codes fail if the clock drifts. Enable time sync with sudo timedatectl set-ntp true.
  • Running google-authenticator with sudo, which creates the secret for root instead of your user.
  • Losing the phone without scratch codes. Use your provider's web console to remove ~/.google_authenticator and set it up again.
  • Forgetting automation accounts, which then fail silently overnight.

Two-factor authentication is one layer. Combine it with the other measures in our SSH security best practices, regular malware scans and the checks in our VPS troubleshooting guide if you ever suspect a break-in.

Why developers choose SkyRain Cloud VPS

Strong access control works best on a server you fully control. SkyRain Cloud Intel VPS plans include:

  • KVM virtualization. Your own kernel and allocated vCores, so you can tune the system the way this guide describes.
  • Intel Xeon Platinum 8269CY hosts. Server-class Cascade Lake CPUs with DDR4 ECC memory.
  • NVMe SSD storage on every plan, which keeps I/O wait low for databases and builds.
  • Full root access to install and configure whatever your stack needs.
  • Unmetered 1 Gbps port in India, close to your users.
  • Simple billing and real support. Monthly billing in rupees with UPI, plus 24/7 tickets, WhatsApp and Discord.

Frequently Asked Questions

Can I use Google Authenticator for SSH logins?
Yes. The libpam-google-authenticator module generates standard TOTP codes that work with Google Authenticator, Microsoft Authenticator and other compatible apps.
Will two-factor authentication break my SSH keys?
No. With AuthenticationMethods publickey,keyboard-interactive, your key is checked first and the code second.
What if I lose my phone?
Use one of the emergency scratch codes created during setup. If you have none, log in through your provider's web console and reset your secret.
Why does SSH keep asking for my password as well as the code?
PAM is still including common-auth. Comment out @include common-auth in /etc/pam.d/sshd if you log in with keys.
How do backup scripts log in if two-factor authentication is required?
Create a separate key-only account for automation and use a Match User block to limit what it can do, rather than removing 2FA for everyone.
Is a hardware security key better than TOTP codes?
Hardware FIDO2 keys are more resistant to phishing and quicker to use, but they cost money and need OpenSSH 8.2 or later on both sides.

Conclusion

Adding two-factor authentication to SSH takes about ten minutes: install the PAM module, enrol each user with an authenticator app, require publickey,keyboard-interactive, and test from a new session before closing the old one. The result is a server where a leaked key is no longer enough to get in. For even stronger protection, consider FIDO2 hardware keys.

For a KVM VPS in India with full root access, see our Intel VPS plans.

SkyRain Cloud Intel Xeon VPS Plans

KVM VPS on Intel Xeon Platinum 8269CY (up to 3.80 GHz Turbo) with DDR4 ECC memory, NVMe SSD, full root access and an unmetered 1 Gbps port.

PlanvCoresRAMStorageNetworkPriceGood forBuy
VPS 1 — Intel28 GB DDR4 ECC40 GB NVMe SSD1 Gbps, unmetered₹649/monthBusiness websites, small apps, scheduled jobs and botsOrder
VPS 2 — Intel416 GB DDR4 ECC80 GB NVMe SSD1 Gbps, unmetered₹1,169/monthBusiness software, mid-size databases, several sites on one serverCheck stock
VPS 3 — Intel832 GB DDR4 ECC150 GB NVMe SSD1 Gbps, unmetered₹2,249/monthERP/CRM stacks, heavier databases, multiple production appsCheck stock
VPS 4 — Intel1664 GB DDR4 ECC250 GB NVMe SSD1 Gbps, unmetered₹4,299/monthHigh-memory workloads and consolidated production serversCheck stock

Prices are monthly in INR as listed on the SkyRain Cloud store (verified 2026-11-23). Live stock and final price are shown at checkout.

Instant UPI • ₹649/mo
Fast KVM Cloud Provisioning