sodcalculator

10 Tech How-To

Two-Factor Authentication on Ubuntu: Setup Guide

Guide 10-42338 · Updated · Step by step

To set up two-factor authentication (2FA) on Ubuntu, you install a PAM module that requires a time-based one-time password (TOTP) in addition to your normal login password. The most common method uses the libpam-google-authenticator package, which works with authenticator apps like Google Authenticator, Authy, or FreeOTP. This guide walks you through the entire process, from installation to configuration, and explains how to handle common issues.

What Is Two-Factor Authentication and Why Use It on Ubuntu?

Two-factor authentication adds a second verification step beyond your password. On Ubuntu, this typically means something you know (your password) plus something you have (a code generated on your phone). Even if an attacker steals your password, they cannot log in without the current code from your authenticator app. This is especially important for servers with SSH access exposed to the internet, where automated password-guessing attacks are constant. Enabling 2FA on your Ubuntu desktop or server dramatically reduces the risk of unauthorized access.

How TOTP Works in Ubuntu

Ubuntu uses the Pluggable Authentication Modules (PAM) system to handle login authentication. The Google Authenticator PAM module implements the Time-based One-Time Password (TOTP) algorithm defined in RFC 6238. Here’s the flow:

  • You install libpam-google-authenticator and run the google-authenticator command to generate a secret key.
  • The secret key is stored in ~/.google_authenticator and also encoded as a QR code or text string.
  • You scan the QR code with an authenticator app on your phone, which stores the secret.
  • Both your phone and the Ubuntu system use the current time to generate a six-digit code that changes every 30 seconds.
  • When you log in, PAM asks for your password and then the current code. The module verifies the code against the stored secret and the current time window.

The system clock must be accurate on both the phone and the Ubuntu machine; otherwise, codes will not match. NTP (Network Time Protocol) is usually enabled by default on Ubuntu, but you should verify it.

Step-by-Step: Install and Configure 2FA on Ubuntu

These steps work for Ubuntu 20.04 LTS and newer versions, both desktop and server. You will need sudo privileges.

  1. Install the PAM module: Open a terminal and run sudo apt update then sudo apt install libpam-google-authenticator.
  2. Run the setup tool: As the user you want to protect, run google-authenticator. It will ask a series of questions. Answer y to generate a time-based token, y to update the config file, y to disallow multiple uses of the same code, y to allow a time skew of 1 minute (recommended), and y to enable rate limiting.
  3. Scan the QR code: The terminal displays a large QR code. Open your authenticator app on your phone and scan it. Alternatively, manually type the secret key shown below the QR code.
  4. Note the emergency scratch codes: The output shows five scratch codes. Write these down and store them safely. They are one-time backup codes if you lose your phone.
  5. Configure PAM for SSH (if you use SSH): Edit the SSH PAM configuration file: sudo nano /etc/pam.d/sshd. Add the following line at the top: auth required pam_google_authenticator.so. Save and exit.
  6. Configure SSH daemon: Edit /etc/ssh/sshd_config and set ChallengeResponseAuthentication yes (or KbdInteractiveAuthentication yes on newer versions). Also set UsePAM yes. Do not disable password authentication yet.
  7. Restart SSH: Run sudo systemctl restart sshd (or ssh on some systems).
  8. Test in a new terminal: Open a new SSH session to your server. You should be prompted for your password and then a verification code. Enter both correctly to confirm it works before closing your current session.

For local desktop login (GDM), the process is slightly different: you add the same PAM line to /etc/pam.d/common-auth instead of the SSH file. However, this can lock you out if you lose your phone, so be extremely careful and always have a backup method.

How to Choose the Right Authenticator App

Any TOTP-compatible app works. The most common choices are:

  • Google Authenticator – the original, simple, and offline. No cloud backup, so losing your phone loses all codes unless you saved the secret.
  • Authy – offers encrypted cloud backup and multi-device sync. Requires a phone number and a master password.
  • FreeOTP – open-source and lightweight, from Red Hat.
  • Bitwarden or 1Password – password managers that also store TOTP secrets, convenient if you already use them.

All of these generate the same codes because they implement the same algorithm. Choose based on your backup preferences and whether you want your 2FA codes in the same app as your passwords.

Common Problems and How to Fix Them

Here are the most frequent issues users encounter and their solutions:

  • Code rejected even though it looks correct: Check the system clock. Run timedatectl to see if time is synchronized. If not, run sudo timedatectl set-ntp true. Also ensure your phone’s time is set to automatic.
  • SSH asks for password but not verification code: The PAM line may be missing or the SSH config not set to use it. Verify both files. Also check that UsePAM yes is present.
  • Locked out of SSH: If you have physical or console access, you can remove the PAM line from /etc/pam.d/sshd or delete the .google_authenticator file for the user. If you don’t have console access, you may need to use a recovery method like a cloud provider’s web console.
  • Codes work but only once per login: This is normal. The module prevents replay attacks by rejecting reused codes. If you log out and back in, you need a new code.
  • Multiple users on the same system: Each user must run google-authenticator separately. The PAM module checks the current user’s ~/.google_authenticator file.

Security Considerations and Best Practices

Two-factor authentication is not a silver bullet. Here are important safety points:

  • Always save the emergency scratch codes in a secure location (e.g., a password manager). If you lose your phone, these are your only way back in.
  • Do not disable password authentication until you have thoroughly tested 2FA in a separate session. Once you are confident, you can set PasswordAuthentication no in sshd_config to force key-based plus 2FA, which is even stronger.
  • Use SSH keys as a fallback: If you have SSH key authentication enabled, you can still log in without 2FA if the key is accepted. To enforce 2FA even for keys, you need to add AuthenticationMethods publickey,keyboard-interactive in sshd_config.
  • Rate limiting is enabled by default in the Google Authenticator module, which locks out after several failed attempts. This helps prevent brute-force attacks.
  • Back up your secret key: When you run google-authenticator, it shows a secret key. Write it down and store it securely. You can use it to re-add the account to a new phone without re-running the setup.

Alternatives to Google Authenticator PAM

While libpam-google-authenticator is the most common, there are alternatives:

  • libpam-oath – Uses the OATH-HOTP/TOTP algorithms and works with a wider range of hardware tokens. Configuration is more complex.
  • YubiKey PAM module – For hardware security keys. Requires a physical YubiKey and the libpam-yubico package.
  • FreeOTP PAM – A newer module that works with the FreeOTP app.
  • SSH key with a hardware token – Instead of a TOTP code, you can use a hardware security key (like a YubiKey) for SSH authentication via PKCS#11. This is more secure but requires additional setup.

For most users, the Google Authenticator module is the best balance of simplicity and security.

Frequently Asked Questions

Can I use 2FA for sudo commands?

Yes, but it is not recommended because it would require a code every time you run a sudo command, which is very annoying. If you want to protect sudo, you can add the PAM line to /etc/pam.d/sudo, but most users prefer to protect only SSH or login.

What if I lose my phone?

Use one of the emergency scratch codes you saved during setup. Each code can be used only once. After using a scratch code, you should immediately generate new ones by running google-authenticator again. If you didn’t save the codes, you will need physical access to the machine to disable 2FA.

Does 2FA work with SFTP or SCP?

Yes, because SFTP and SCP use the same SSH authentication mechanism. However, some SFTP clients may not support interactive keyboard prompts for the verification code. In that case, you may need to use a client that does, or use SSH keys instead.

Can I have multiple authenticator apps for the same account?

Yes. When you run google-authenticator, it shows a secret key. You can manually enter that secret into multiple apps on different devices. All will generate the same codes. This is a good backup strategy.

Is it safe to use 2FA on a desktop Ubuntu machine?

Yes, but be aware that if you enable it for local login (GDM), you will need a code every time you log in at the physical console. This is fine for most users, but if you use automatic login or need to log in without a phone nearby, it can be inconvenient. Consider using it only for SSH if that is your primary access method.

Does 2FA protect against all attacks?

No. It protects against password theft and brute-force attacks, but not against malware on your machine that can intercept the code, or phishing attacks that trick you into entering the code on a fake site. Always keep your system updated and be cautious about what you run.

Related

General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.

More in this bed

The whole Tech How-To bed →