Two-factor authentication (2FA) on Ubuntu Server via Google Authenticator

A one-time code from your phone for SSH, sudo and the console. Follows the SSH keys guide.

You tick where to require the code (SSH, sudo, console login), generate a secret key into your phone and turn it on. Password login over SSH stays off; you can allow it for users without a key, but only together with the code.

Vladimír NeporAuthorVladimír Nepor
PublishedUpdated
SSH login has two steps: first the key from your computer, then a one-time code from the phone app. The server keeps refusing password login.1 · keyyour computer2 · code482913phone appserverpublickey ✓keyboard-interactive ✓password ✕02 · PHONEApp and secret keyQR code and emergency codeschapter →03 · SETUPTurning on 2FASSH, sudo and console by your choicechapter →03 · OPTIONALsudo and consolethe code for admin commands toochapter →04 · RECOVERYLost phoneemergency codes and undochapter →
Contents

01 · Start

Before you start

You add a one-time code from a phone app to the SSH key. Someone who gets your key together with its passphrase still cannot get in without the phone.

Prerequisites

A server with the correct time (a code is valid for 30 seconds). For SSH also the SSH keys guide done. For a server reachable from the internet 2FA is recommended, with access from the home network or via Tailscale it is optional, see Securing access.

Where do you want to require the code?

Tick everything you want to protect. Only the steps you need are shown.

02 · Phone

App and secret keys

Install an app for one-time codes on your phone, e.g. Google Authenticator, Microsoft Authenticator, 2FAS or Aegis. The next steps are on the server.

Step 1: Install the PAM module

Terminal
sudo apt update && sudo apt install libpam-google-authenticator

Step 2: Check that the server has the correct time

The code is computed from the time. With a time difference the server rejects correct codes:

Terminal
timedatectl | grep -E 'synchronized|NTP service'
Output
System clock synchronized: yes
              NTP service: active

If the result is no, set up time synchronization.

Step 3: Generate the secret key and load it into your phone

As your user, without sudo. Scan the QR code with the app and type in the code it shows. Answer the questions y, y, y, n, y (table below).

Terminal
google-authenticator    # as your user, without sudo

The program's questions and what to answer:

QuestionAnswer
…tokens to be time-based?y: time-based codes
…update your "~/.google_authenticator" file?y: saves the secret key
…disallow multiple uses of the same authentication token?y: each code can be used only once
…increase the window from its default size…?n: with the correct time no extra tolerance is needed
…enable rate-limiting?y: at most 3 attempts per 30 seconds

Step 4: Other users? A secret key for them too

Only if other people use the server too. Each of them then needs the code for what you ticked above, before you turn it on, or they cannot log in. This includes users without a key from the ssh-password group. Everyone has their own secret key; their phone scans the QR code:

Terminal
sudo -iu <USER> google-authenticator
Keep the emergency codes

Below the QR code are five emergency codes. Store them outside the phone (password manager, paper in a safe). If you lose the phone they let you in.

03 · Setup

Turning on 2FA

Keep two windows open

The changes do not drop existing connections. Test the new configuration in another window and close the first one only once the login with the code works.

For SSH

Your details: the commands in this guide are filled in from them. They are stored only in your browser and other Ubuntu guides use them too.

Your admin account (with sudo) created during the Ubuntu installation. Not root and not common names like admin, ubuntu or user. Bots try those first.

Invalid value, the commands keep the placeholder.

IP address in your local network (see your router or run ip -4 addr on the server), a Tailscale address or a domain name.

Invalid value, the commands keep the placeholder.

File name of the key in ~/.ssh. One key per server (or group of servers). The name makes it easy to find and revoke.

Invalid value, the commands keep the placeholder.

Optional change of the default port 22. It reduces log noise; real protection comes from key login and the firewall. Range 1024 to 49151.

Invalid value, the commands keep the placeholder.

Step 5: SSH: the code instead of the password

The /etc/pam.d/sshd file decides what SSH asks for. After the key it will ask for the code. The password only members of the ssh-password group who log in without a key (SSH keys guide). The output should match the second block:

Terminal
[ -f /etc/pam.d/sshd.bak ] || sudo cp /etc/pam.d/sshd /etc/pam.d/sshd.bak
sudo groupadd -f ssh-password
grep -q pam_google_authenticator /etc/pam.d/sshd || sudo sed -i 's/^@include common-auth$/auth [success=1 default=ignore] pam_succeed_if.so quiet user notingroup ssh-password\nauth substack common-auth\nauth required pam_google_authenticator.so/' /etc/pam.d/sshd
grep -A2 pam_succeed_if /etc/pam.d/sshd
Output
auth [success=1 default=ignore] pam_succeed_if.so quiet user notingroup ssh-password
auth substack common-auth
auth required pam_google_authenticator.so

Step 6: Allow the second login step in 00-hardening.conf

The file from the SSH keys guide. Two lines change, everything else including the port stays: KbdInteractiveAuthentication to yes (SSH may ask for the code) and AuthenticationMethods to publickey,keyboard-interactive (the key first, then the code).

Terminal
sudo sed -i -E 's/^KbdInteractiveAuthentication .*/KbdInteractiveAuthentication yes/; s/^AuthenticationMethods .*/AuthenticationMethods publickey,keyboard-interactive/' /etc/ssh/sshd_config.d/00-hardening.conf
cat /etc/ssh/sshd_config.d/00-hardening.conf
Output
# Port <SSH_PORT>    (optional: uncomment and set your own port)
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication yes
PermitRootLogin no
AuthenticationMethods publickey,keyboard-interactive
AllowGroups ssh-users

Step 7: Apply the settings and log in from a new window

SSH restart, check of the effective settings and the login: key passphrase, then the code.

Ubuntu 22.04, 24.04, 26.04
sudo sshd -t && sudo systemctl restart ssh
Terminal
sudo sshd -T | grep -E '^(usepam|passwordauthentication|kbdinteractiveauthentication|authenticationmethods) '
Output
usepam yes
passwordauthentication no
kbdinteractiveauthentication yes
authenticationmethods publickey,keyboard-interactive
Terminal
ssh -i ~/.ssh/<KEY_NAME> -o IdentitiesOnly=yes -p 22 <ADMIN_USER>@<SERVER_IP>
Output
Enter passphrase for key '…<KEY_NAME>':
(<ADMIN_USER>@<SERVER_IP>) Verification code:

A user without a key (the ssh-password group) logs in with a password and the code:

Terminal
ssh -p 22 <USER>@<SERVER_IP>
Output
(<USER>@<SERVER_IP>) Password:
(<USER>@<SERVER_IP>) Verification code:

For sudo

Step 8: sudo: password and code

Keep an admin session (sudo -i) open in one window until sudo with the code works in another one.

Terminal
[ -f /etc/pam.d/sudo.bak ] || sudo cp /etc/pam.d/sudo /etc/pam.d/sudo.bak
grep -q pam_google_authenticator /etc/pam.d/sudo || sudo sed -i '/^@include common-auth/a auth required pam_google_authenticator.so' /etc/pam.d/sudo
grep -E 'common-auth|google_authenticator' /etc/pam.d/sudo
Output
@include common-auth
auth required pam_google_authenticator.so
Terminal
sudo -k && sudo true    # in a second window: password, then Verification code

For console login

Step 9: Console login: password and code

Then not even the password at the server in person is enough: without the emergency codes and the phone you cannot get in. On Ubuntu Desktop run the same command with the /etc/pam.d/gdm-password file too (graphical login). Test it on another console (Ctrl+Alt+F3) while SSH or the current console session is still open.

Terminal
[ -f /etc/pam.d/login.bak ] || sudo cp /etc/pam.d/login /etc/pam.d/login.bak
grep -q pam_google_authenticator /etc/pam.d/login || sudo sed -i '/^@include common-auth/a auth required pam_google_authenticator.so' /etc/pam.d/login
grep -A1 '^@include common-auth' /etc/pam.d/login
Output
@include common-auth
auth required pam_google_authenticator.so

04 · Recovery

Lost phone and undo

Lost phone

  • You have an emergency code: enter it instead of the app code (each works once). Then run google-authenticator again and load the new secret key into the new phone.
  • You have nothing: log in at the server console with your password and run google-authenticator as your user. This works unless console login is ticked; then the console asks for the code too.

Undo

For SSH

Restores PAM for SSH from the backup and reverts both lines in 00-hardening.conf. Users without a key then cannot log in:

Terminal
sudo cp /etc/pam.d/sshd.bak /etc/pam.d/sshd
sudo sed -i -E 's/^KbdInteractiveAuthentication .*/KbdInteractiveAuthentication no/; s/^AuthenticationMethods .*/AuthenticationMethods publickey/' /etc/ssh/sshd_config.d/00-hardening.conf
sudo sshd -t && sudo systemctl restart ssh

For sudo

Terminal
sudo cp /etc/pam.d/sudo.bak /etc/pam.d/sudo

For console login

Terminal
sudo cp /etc/pam.d/login.bak /etc/pam.d/login

05 · Problems

Troubleshooting

Watch the SSH server log in a second window and try to log in:

Terminal
sudo journalctl -u ssh -f    # on the server: watch the log while you try to log in
Message / stateCause and fix
A correct code is rejectedthe server time is off, see step 2
It never asks for the codethe change from step 6 is missing in 00-hardening.conf
After the key it asks for the password and the codethe user is in the ssh-password group, or the change from step 5 is missing
Permission denied (keyboard-interactive)the user has no ~/.google_authenticator (step 4)
The same code does not work twiceby design: each code works only once, wait for the next one

Sources

Official documentation and further reading

Need a secure server setup?

We design, secure and document networks and servers.

Servers & Networks