Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
VGSources
Blog

How to Set Up Multi-Factor Authentication for SSH on a Linux VPS

Configure Ubuntu SSH so every login requires both an authorized SSH key and a PAM-validated TOTP code, with version notes, testing steps, troubleshooting, recovery, and FIDO alternatives.
Length10 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

On an Ubuntu VPS, the most reliable SSH MFA design is a two-step sequence: the server first verifies the user’s SSH public key, then asks for a time-based one-time password (TOTP) through PAM. Password authentication is disabled, so a stolen password alone cannot satisfy the login policy. The critical safety rule is to prove that key access works and enroll the account’s authenticator before making the two-factor sequence mandatory.

What SSH MFA does in this setup

SSH multi-factor authentication is not a single switch. OpenSSH runs an ordered authentication policy, and the account must complete every method in the selected sequence. In the Ubuntu design documented for TOTP, the sequence is:

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Public key: the SSH client proves possession of the private key corresponding to a key authorized for the account.
  2. Keyboard-interactive through PAM: the server invokes PAM, which asks for and validates a TOTP or HOTP code generated by the user’s authenticator.

The key requirement is expressed as AuthenticationMethods publickey,keyboard-interactive. The comma means both methods in that list must succeed, in that order. This is different from listing methods as alternatives: OpenSSH considers a comma-separated list a complete required sequence, while separate lists represent acceptable alternatives.

The recommended policy also sets PasswordAuthentication no. Ubuntu describes the result as public-key authentication being the first factor, the TOTP/HOTP code the second, and password authentication unavailable. A user therefore needs both the private key and the enrolled one-time-code device.

#1 Best Overall
Yubico - YubiKey 5C NFC - Multi-Factor authentication (MFA) Security Key and passkey, Connect via USB-C or NFC, FIDO Certified - Protect Your Online Accounts
  • POWERFUL SECURITY KEY: The YubiKey 5C NFC is the most versatile physical passkey, protecting your digital life from phishing attacks. It ensures only you can access your accounts
  • WORKS WITH 1000+ ACCOUNTS: Compatible with popular accounts like Google, Microsoft, and Apple. A single YubiKey 5C NFC secures 100+ of your favorite accounts, including email, password managers, and more
  • FAST & CONVENIENT LOGIN: Plug in your YubiKey 5C NFC via USB and tap it, or tap it against your phone (NFC), to authenticate. No batteries, no internet connection, and no extra fees required
  • MOST SECURE PASSKEY: Supports FIDO2/WebAuthn, FIDO U2F, Yubico OTP, OATH-TOTP/HOTP, Smart card (PIV), and OpenPGP. That means it’s versatile, working almost anywhere you need it
  • PRIMARY & SPARE KEYS: Just like having a spare house key, we recommend buying two YubiKeys - one for daily use and one as a spare. That way you’ll never get locked out of your accounts

Before changing SSH: prevent a lockout

A mandatory MFA policy can lock out an account that has not yet enrolled a code or does not have a working key. Treat the change as a live access migration, not as a routine package installation.

  • Open a second SSH session, or keep the VPS provider’s out-of-band console available.
  • In the existing session, verify that the target account can log in with its SSH key. Do not assume a key is usable merely because a public key appears in ~/.ssh/authorized_keys.
  • Enroll the account’s TOTP secret while the current session is still available.
  • Only then enable AuthenticationMethods publickey,keyboard-interactive and disable password authentication.
  • Keep the original session and console open until a completely new MFA login succeeds.

For a multi-user VPS, repeat the enrollment process for every account that will be subject to the policy. A user without both a working key and a TOTP enrollment will fail the required sequence.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Ubuntu package and version requirements

This procedure targets Ubuntu Server and uses Ubuntu’s libpam-google-authenticator package. The package supplies the PAM module used to validate TOTP or HOTP codes. Ubuntu ships it in the universe archive component, which receives best-effort community support rather than the same support commitment as packages in the main component. Package behavior and configuration labels can therefore vary with the Ubuntu release.

Current Ubuntu releases use KbdInteractiveAuthentication in sshd_config. Ubuntu 20.04 and earlier may use the older name, ChallengeResponseAuthentication, for the same keyboard-interactive capability. Check the directive already present in your configuration before adding a duplicate with a conflicting value.

Set up SSH key plus TOTP on Ubuntu

1. Keep the recovery path open

Start from the still-working SSH session. Open another terminal and authenticate to the same account with the key you intend to keep using. If that test fails, repair key access first; enforcing MFA will not fix an already broken key login.

Have the VPS console ready as a final recovery route. It should let you log in locally or edit the SSH and PAM files if a daemon reload exposes a syntax or authentication mistake.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

2. Install the PAM module

Refresh package metadata and install the module:

sudo apt update
sudo apt install libpam-google-authenticator

Do not remove the open SSH session after installation. The package is only the validator; SSH will not ask for a code until PAM and the sshd authentication policy are configured.

3. Add the PAM rule for sshd

Edit /etc/pam.d/sshd with an editor available on the server and add this authentication rule:

Rank #2
Yubico - Security Key C NFC - Basic Compatibility - Multi-Factor authentication (MFA) Security Key and passkey, Connect via USB-C or NFC, FIDO Certified
  • POWERFUL SECURITY KEY: The Security Key C NFC is the essential physical passkey for protecting your digital life from phishing attacks. It ensures only you can access your accounts.
  • WORKS WITH 1000+ ACCOUNTS: Compatible with Google, Microsoft, and Apple. A single Security Key C NFC secures 100 of your favorite accounts, including email, password managers, and more.
  • FAST & CONVENIENT LOGIN: Plug in your Security Key C NFC via USB-C and tap it, or tap it against your phone (NFC) to authenticate. No batteries, no internet connection, and no extra fees required.
  • TRUSTED PASSKEY TECHNOLOGY: Uses the latest passkey standards (FIDO2/WebAuthn & FIDO U2F) but does not support One-Time Passwords. For complex needs, check out the YubiKey 5 Series.
  • BUILT TO LAST: Made from tough, waterproof, and crush-resistant materials. Manufactured in Sweden and programmed in the USA with the highest security standards.
auth required pam_google_authenticator.so

required means the PAM check must succeed for the authentication stack to succeed. The rule connects SSH’s keyboard-interactive exchange to the per-user secret created in the enrollment step. Keep the line in the authentication section; placing it in an unrelated PAM file will not make sshd validate the code.

4. Configure the sshd method sequence

Edit /etc/ssh/sshd_config. For current Ubuntu releases, add or verify the following settings:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
PubkeyAuthentication yes
UsePAM yes
KbdInteractiveAuthentication yes
PasswordAuthentication no
AuthenticationMethods publickey,keyboard-interactive

On Ubuntu 20.04 and earlier, use the older directive name instead:

ChallengeResponseAuthentication yes

Do not enable both names with contradictory values. The important behavior is that keyboard-interactive authentication is enabled, PAM is enabled, and the method sequence requires a public key followed by keyboard-interactive authentication.

AuthenticationMethods controls what sshd offers next. With publickey,keyboard-interactive, a successful key exchange completes only the first stage; sshd must then offer the PAM-backed challenge. Leaving out the method line allows other enabled methods to satisfy the login, and leaving out keyboard-interactive prevents the code prompt from appearing.

Before reloading a production daemon, validate the file’s syntax:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo sshd -t

A silent result indicates that the configuration parsed successfully. If the command reports an error, correct it before attempting a reload.

5. Enroll each user’s authenticator

Run the enrollment command as the account that will log in with MFA, not as an unrelated administrator:

Rank #3
Yubico - YubiKey 5 NFC - Multi-Factor authentication (MFA) Security Key and passkey, Connect via USB-A or NFC, FIDO Certified - Protect Your Online Accounts
  • POWERFUL SECURITY KEY: The YubiKey 5 NFC is the most versatile physical passkey, protecting your digital life from phishing attacks. It ensures only you can access your accounts
  • WORKS WITH 1000+ ACCOUNTS: Compatible with popular accounts like Google, Microsoft, and Apple. A single YubiKey 5 NFC secures 100+ of your favorite accounts, including email, password managers, and more
  • FAST & CONVENIENT LOGIN: Plug in your YubiKey 5 NFC via USB and tap it, or tap it against your phone (NFC), to authenticate. No batteries, no internet connection, and no extra fees required
  • MOST SECURE PASSKEY: Supports FIDO2/WebAuthn, FIDO U2F, Yubico OTP, OATH-TOTP/HOTP, Smart card (PIV), and OpenPGP. That means it’s versatile, working almost anywhere you need it
  • PRIMARY & SPARE KEYS: Just like having a spare house key, we recommend buying two YubiKeys - one for daily use and one as a spare. That way you’ll never get locked out of your accounts
google-authenticator

The interactive setup displays a secret and a QR code. Use a TOTP-compatible authenticator app to scan the QR code, then follow the prompts with these choices:

  • Choose time-based tokens when asked which token type to create.
  • Allow the command to update the user’s secret file.
  • Disallow reuse of a previously accepted token.
  • Decline the extended time window unless clock drift or a specific operational requirement makes it necessary.
  • Enable rate limiting to slow repeated guessing attempts.

Write the emergency scratch codes down and store them offline in a protected location. They are intended for recovery if the authenticator device is unavailable. Protect the generated secret file as carefully as the account’s private key, and do not place it in an unencrypted synchronization service. The QR code and secret are equivalent credentials: anyone who obtains them can generate valid codes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Repeat enrollment for every account that will be required to complete the PAM method. Enrollment must happen before the mandatory method sequence is applied to that user.

6. Reload sshd and perform a new-login test

Apply the daemon changes without closing the known-good session:

sudo systemctl try-reload-or-restart ssh

The command attempts a reload and can restart the service if a reload is not available. Leave the original session open. From a separate terminal, connect normally and confirm this order:

  1. Your SSH client offers the authorized private key.
  2. The server accepts the key as the first method.
  3. The client displays a keyboard-interactive prompt for the verification code.
  4. The current code from the authenticator app completes the login.

If the new connection fails, use the still-open session or console to inspect the effective sshd configuration and the PAM rule. Do not close every administrative connection simply because the service reported a successful reload.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Verify the effective policy

A configuration file can contain an earlier setting, an included fragment, or a release-specific directive that changes the result you expect. Inspect the effective configuration as root when troubleshooting:

sudo sshd -T | grep -E 'authenticationmethods|pubkeyauthentication|usepam|passwordauthentication|kbdinteractiveauthentication|challengeresponseauthentication'

The exact output depends on the Ubuntu release. You are looking for public-key authentication enabled, PAM enabled, password authentication disabled, keyboard-interactive enabled under the directive supported by that release, and the required method sequence present.

Rank #4
Yubico - Security Key NFC - Basic Compatibility - Multi-Factor Authentication (MFA) Key, Connect via USB-A or NFC, FIDO Certified
  • POWERFUL SECURITY KEY: The Security Key NFC is the essential physical passkey for protecting your digital life from phishing attacks. It ensures only you can access your accounts.
  • WORKS WITH 1000+ ACCOUNTS: Compatible with Google, Microsoft, and Apple. A single Security Key NFC secures 100 of your favorite accounts, including email, password managers, and more.
  • FAST & CONVENIENT LOGIN: Plug in your Security Key NFC via USB-A and tap it, or tap it against your phone (NFC) to authenticate. No batteries, no internet connection, and no extra fees required.
  • TRUSTED PASSKEY TECHNOLOGY: Uses the latest passkey standards (FIDO2/WebAuthn & FIDO U2F) but does not support One-Time Passwords. For complex needs, check out the YubiKey 5 Series.
  • BUILT TO LAST: Made from tough, waterproof, and crush-resistant materials. Manufactured in Sweden and programmed in the USA with the highest security standards.

Test from a new terminal rather than reusing an existing connection. An already authenticated session does not prove that the new policy is working.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting common failures

The key works but SSH never asks for a code

This usually means the keyboard-interactive stage is unavailable or the method sequence does not require it. Check all of the following:

  • UsePAM yes is present.
  • KbdInteractiveAuthentication yes is present on current releases, or ChallengeResponseAuthentication yes is present on older Ubuntu releases.
  • AuthenticationMethods publickey,keyboard-interactive is present and spelled exactly.
  • The PAM line auth required pam_google_authenticator.so is in /etc/pam.d/sshd.
  • The daemon was successfully reloaded after the edits.

OpenSSH offers only methods that are enabled and valid as the next stage of the configured sequence. If any of those controls is missing, a key-only login can succeed without a prompt.

The code prompt appears, but every code is rejected

Confirm that the user enrolled with google-authenticator and that the secret file belongs to that user. Check the server clock and the authenticator device clock; time-based tokens depend on both being reasonably synchronized. If the user enabled an intentionally narrow token window, even modest clock drift can cause rejection.

Do not repeatedly guess codes. The enrollment choices include rate limiting, and repeated failures can make diagnosis harder. Use a scratch code only for the documented recovery situation, then create a new enrollment if the secret may have been exposed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The private key is rejected before the code stage

MFA does not replace ordinary SSH key requirements. Verify that the client is offering the expected private key, the matching public key remains in the account’s authorized_keys, and the account and file permissions permit sshd to read it. Test key access while the old session remains open; do not weaken the new MFA policy to compensate for a missing or incorrect key.

Password plus code was the intended design

The documented Ubuntu recipe is deliberately a key-plus-code policy and sets PasswordAuthentication no. Do not copy it unchanged if your operational requirement is password-plus-code. That design has a different first method and different exposure, so its AuthenticationMethods list, password setting, and PAM stack must be planned and tested separately.

A reload succeeds but new sessions still behave differently

Check whether sshd is reading a different configuration file or an included fragment, then inspect the effective values with sshd -T. Also confirm that you reloaded the service actually accepting connections; distributions can use different service names, although Ubuntu’s service is normally ssh. Keep the console or existing session available while correcting the policy.

Best Value
Thetis FIDO2 Security Key (USB-A, 2-Pack) - Hardware MFA & Passkey Access for Business, School ERP & Employee Accounts | Compatible with Windows, Google Workspace, Apple ID, Coinbase, Salesforce
  • FIDO2 & Passkey Ready: Business-ready and FIDO2 L1 certified. This key is supported by major management suites and is ideal for both individual and enterprise deployment. Works seamlessly with Gmail, Facebook, GitHub, Dropbox, Coinbase, and more.
  • Universal Connectivity (USB-A ): Features a built-in USB-A connector—simply unfold the key and plug it into your compatible PC or laptop for seamless authentication on the go.
  • Dedicated Manager App: Use the Thetis Manager App for the initial hardware PIN setup. Setting the PIN on the device first ensures a smooth registration process. Once the PIN is configured, you can begin registering the key across your favorite FIDO2-compatible online services.
  • Ultra-Durable & Portable: Featuring a rotating metal cover, this key is water, crush, and tamper-resistant. It fits easily on a keychain and requires no batteries or network connectivity.
  • Check FIDO2 compatibility before purchase - Known limitations: ID Austria is not supported (requires FIDO2 Level 2). Windows Hello login only works with Windows Enterprise editions that support Entra ID, and NFC is NOT supported.

You are locked out

Use the VPS console or an existing administrative session. Restore a temporary working configuration, correct the PAM or sshd setting, and reload the service from that recovery path. Once key access and TOTP enrollment are confirmed, reapply the mandatory sequence and test from a second terminal. Never test a lockout-prone change by terminating the only successful session.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recovery and lockout-avoidance checklist

  • Have two independent access paths: an existing SSH session plus a console or second session.
  • Confirm the exact key-based login before changing sshd.
  • Enroll and test each user’s authenticator before enforcing the sequence.
  • Store scratch codes offline and restrict access to them.
  • Protect each user’s secret file and avoid unencrypted synchronization.
  • Run sshd -t before a reload.
  • Use systemctl try-reload-or-restart ssh while a known-good session remains open.
  • Test a brand-new connection and observe both stages.
  • Keep the recovery path until the new login has succeeded and logs show expected behavior.

TOTP versus a FIDO hardware key

TOTP through PAM is useful when users already have an authenticator app and the VPS can install Ubuntu’s PAM module. It requires per-user enrollment, protection of the shared secret, and a recovery process for lost devices. The code is typed into the SSH keyboard-interactive exchange.

OpenSSH also documents FIDO authenticator algorithms for deployments with compatible clients and security keys. The touch-required control requires physical user presence, while verify-required requires user verification such as a PIN. A FIDO2 key can therefore provide a hardware-backed alternative to an app-generated code, but support must be checked across the OpenSSH client, server, operating system, and key.

  • Device availability: TOTP works on an enrolled authenticator app; FIDO requires a compatible physical key and client.
  • Phishing resistance: a FIDO credential is designed to bind authentication to the legitimate origin, while a manually entered TOTP can be relayed by a phishing site.
  • Loss recovery: TOTP relies on protected scratch codes or re-enrollment; FIDO deployments generally require a spare enrolled key or an administrative recovery procedure.
  • Fleet management: both approaches need enrollment and revocation processes, but their hardware, client, and inventory requirements differ.
  • Compatibility: test the exact OpenSSH versions and client libraries used by the fleet before making a hardware-key method mandatory.

Ubuntu cautions that its documented mandatory TOTP/HOTP configuration has not been tested in combination with mandatory U2F/FIDO. Do not require both stacks at once in production without testing a non-production account, the recovery path, and every client type that must connect.

Operational guidance after deployment

Enroll and revoke deliberately

When a user joins, create or verify the SSH key access first, enroll the TOTP secret second, and only then place the account under the mandatory method policy. When a device is lost, revoke or replace the affected secret and invalidate the corresponding SSH key if there is any chance the key was exposed. Scratch codes should be treated as emergency credentials, not as a routine login method.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Separate testing from production enforcement

Use a test account or staging VPS to validate changes to PAM, OpenSSH versions, FIDO settings, and authenticator behavior. Include a fresh login, an expired or invalid code, a missing key, a lost-device recovery, and a console-based rollback in the test plan. Distribution updates can rename directives or alter package behavior, so recheck the effective configuration after major upgrades.

Know what this policy does not cover

This setup protects the SSH authentication exchange; it does not repair a compromised VPS, protect an already stolen private key, or make an insecure workstation trustworthy. Restrict administrative accounts, protect private keys with appropriate local controls, monitor authentication logs, and keep the operating system patched. MFA should be one layer in the server’s access model, not the only one.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.