How to Set Up Two-Factor Authentication for SSH on Your VPS

How to Set Up Two-Factor Authentication for SSH on Your VPS

A password alone is a weak lock on your server. Bots probe SSH on every VPS, trying common passwords around the clock, and one guessed password hands them a shell. Setting up two-factor authentication for ssh adds a second check: even with the right password, nobody gets in without a time-based code from your phone. This guide covers the full setup on Ubuntu with the Google Authenticator PAM module, plus SSH keys, backup codes, and how to recover if you lock yourself out.

How Two-Factor Authentication for SSH Works

SSH two-factor authentication pairs something you know (your password or key) with something you have (your phone). The server and your authenticator app share a secret key. Both sides combine that secret with the current time to produce the same six-digit code, which changes every 30 seconds. That is the TOTP system, short for time-based one-time password. At login, the server checks the code you type against its own calculation. A stolen password is useless on its own because the attacker does not have your phone, and a code seen over your shoulder is useless 30 seconds later. Each totp ssh login uses a fresh code, so replaying an old one never works.

The moving parts are small: the libpam-google-authenticator package provides a PAM module that generates the secret and checks codes, OpenSSH hands the login to PAM when ChallengeResponseAuthentication is set to yes, and your phone runs any TOTP app, such as Google Authenticator or FreeOTP. Nothing here needs a paid service.

What You Need Before You Start

Before you change anything, have these in place:

  • A VPS running Ubuntu 22.04 or 24.04 with root or sudo access. The ssh two-factor authentication ubuntu steps below use apt and the standard OpenSSH server.
  • A second SSH session already open to the server. Keep it open until the new login works in a fresh session; if you break the config, it is your way back in.
  • A TOTP app on your phone. Any app that supports standard TOTP codes works.
  • A roughly correct clock. TOTP depends on time, so check the server clock with timedatectl before you start.

Do not log out of all sessions until a new login with the code has worked. Every lockout story starts with someone editing sshd_config, restarting the service, and closing their only session.

Install Google Authenticator on Your VPS

The ssh google authenticator setup starts with one package:

sudo apt update
sudo apt install libpam-google-authenticator -y

Run the setup command as the user who will log in with 2FA, not as root, because the secret is stored per user.

google-authenticator

The command asks a series of questions:

  • Do you want authentication tokens to be time-based? Yes. Time-based tokens are the standard.
  • Do you want me to update your “~/.google_authenticator” file? Yes, this writes the secret to your home directory.
  • Do you want to disallow multiple uses of the same authentication token? Yes, this blocks code reuse.
  • Do you want the time skew window increased to 4 minutes? No. The default window is enough when both clocks are synced.
  • Do you want to enable rate-limiting? Yes, this blocks repeated wrong codes.

Before the questions, the command prints a QR code, a secret key, and five emergency scratch codes. Scan the QR code with your authenticator app, or type the secret in by hand. Then write the scratch codes on paper and store them somewhere safe, not in a file on the same server. Those codes are your spare keys. If you lose your phone, they are the only way back in.

Configure SSH to Require the Code

Installing the PAM module changes nothing until OpenSSH is told to use it. Open /etc/ssh/sshd_config and set these three lines:

ChallengeResponseAuthentication yes
AuthenticationMethods publickey,password publickey,keyboard-interactive
UsePAM yes

What each line does:

  • ChallengeResponseAuthentication yes lets the server ask for the code during login.
  • AuthenticationMethods lists the combinations that count as a full login: a public key plus either a password or a keyboard-interactive prompt. The keyboard-interactive prompt is the one PAM uses to ask for the TOTP code.
  • UsePAM yes switches PAM on for SSH, which lets the Google Authenticator module run.

Next, tell PAM to call the module. Open /etc/pam.d/sshd and add this line at the top:

auth required pam_google_authenticator.so

On Ubuntu, keeping @include common-auth after the authenticator line is fine; the order decides what runs first. Save both files and check the config before restarting:

sudo sshd -t
sudo systemctl restart ssh

If sshd -t reports an error, fix it before restarting; a bad config stops SSH from starting. Now open a new terminal and log in. You should see the password prompt, then a “Verification code:” prompt. Enter the six digits from your app. If both pass, 2FA is live. Do not close your original session until this test succeeds. If the code is rejected, check the server time first: a clock off by more than a couple of minutes breaks TOTP silently.

Add the Account to Your Authenticator App

Scan the code while the setup command is still on screen, then confirm the app shows a six-digit code that changes every 30 seconds, labeled with your server hostname. If the label is wrong, delete the entry and scan again. Typing the secret by hand works too, but one wrong character produces codes the server will never accept, so scanning is safer.

Each user who logs in over SSH needs their own secret, so run google-authenticator separately for each account and store each scratch code set with the matching username. A shared secret defeats the point: revoking one person means rotating it for everyone.

Test the code against a fresh login: type a code, wait for it to expire, and type the next one. If the second code also works, the time window and the secret are both correct. For a fuller lockdown, read our guide to hardening SSH on Ubuntu 24.04, which covers ten config changes that pair well with two-factor authentication.

Combine Two-Factor Authentication with SSH Keys

The strongest setup is a key plus a code: an attacker needs both your private key file and your phone. The config above already does this, since AuthenticationMethods publickey,keyboard-interactive checks the key first and the TOTP code second.

If you have not set up keys yet, generate one on your computer and copy it to the server:

ssh-keygen -t ed25519 -C "laptop"
ssh-copy-id user@your-server-ip

Then tighten the server side: in sshd_config, set PasswordAuthentication no so a password alone never logs anyone in, and keep AuthenticationMethods publickey,keyboard-interactive so the code is still required after the key. Restart SSH and test from a new session. The flow becomes key first, then code. For the full walkthrough, see how to set up SSH keys on a new VPS. Once keys are your only first factor, read how to disable SSH password login to close the password path for good.

Login method First factor Second factor Password alone works?
Password only Password None Yes
Password + TOTP Password Code from app No
Key + TOTP SSH key Code from app No
Key only SSH key None No

Key plus TOTP is the row to aim for. Password plus TOTP is a big step up from a bare password, but it still leaves password guessing on the table. Keys remove the guessing entirely.

What to Do If You Get Locked Out

Lockouts usually come from a lost phone or a mistyped secret. Work through these in order:

  1. Use a scratch code. At the verification prompt, type one of the five emergency codes instead of a TOTP code. Each code works once. Log in, run google-authenticator again for a fresh secret, and update your app.
  2. Use your open session. If you kept a second session open, you are already in: remove or comment out the pam_google_authenticator.so line in /etc/pam.d/sshd, restart SSH, and log in normally to redo the setup.
  3. Use your provider console. Most VPS providers offer a web console that gives you a shell without SSH. From there, edit the same PAM file or delete ~/.google_authenticator for the locked account, then restart SSH.
  4. Boot recovery mode. If there is no console, boot into recovery, mount the root disk, and remove the PAM line. It is slower, but it never goes through SSH at all.

After you are back in, fix the actual cause first: a wrong secret, a drifted clock, or a lost phone. Then test the login again from a new session. A recovery you have not tested is a recovery you do not have. As a final layer, set up Fail2ban for SSH so repeated wrong passwords and codes get blocked at the firewall.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.