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.
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.
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.
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
sudo apt update && sudo apt install libpam-google-authenticatorStep 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:
timedatectl | grep -E 'synchronized|NTP service'System clock synchronized: yes
NTP service: activeIf 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).
google-authenticator # as your user, without sudoThe program's questions and what to answer:
| Question | Answer |
|---|---|
| …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:
sudo -iu <USER> google-authenticatorBelow 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
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
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:
[ -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/sshdauth [success=1 default=ignore] pam_succeed_if.so quiet user notingroup ssh-password
auth substack common-auth
auth required pam_google_authenticator.soStep 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).
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# Port <SSH_PORT> (optional: uncomment and set your own port)
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication yes
PermitRootLogin no
AuthenticationMethods publickey,keyboard-interactive
AllowGroups ssh-usersStep 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.
sudo sshd -t && sudo systemctl restart sshsudo sshd -T | grep -E '^(usepam|passwordauthentication|kbdinteractiveauthentication|authenticationmethods) 'usepam yes
passwordauthentication no
kbdinteractiveauthentication yes
authenticationmethods publickey,keyboard-interactivessh -i ~/.ssh/<KEY_NAME> -o IdentitiesOnly=yes -p 22 <ADMIN_USER>@<SERVER_IP>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:
ssh -p 22 <USER>@<SERVER_IP>(<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.
[ -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@include common-auth
auth required pam_google_authenticator.sosudo -k && sudo true # in a second window: password, then Verification codeFor 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.
[ -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@include common-auth
auth required pam_google_authenticator.so04 · 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-authenticatoragain 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-authenticatoras 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:
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 sshFor sudo
sudo cp /etc/pam.d/sudo.bak /etc/pam.d/sudoFor console login
sudo cp /etc/pam.d/login.bak /etc/pam.d/login05 · Problems
Troubleshooting
Watch the SSH server log in a second window and try to log in:
sudo journalctl -u ssh -f # on the server: watch the log while you try to log in| Message / state | Cause and fix |
|---|---|
| A correct code is rejected | the server time is off, see step 2 |
| It never asks for the code | the change from step 6 is missing in 00-hardening.conf |
| After the key it asks for the password and the code | the 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 twice | by design: each code works only once, wait for the next one |
Sources
Official documentation and further reading
The guide is based on the module and OpenSSH documentation (verified on 29 Oct 2026):
- google-authenticator-libpamThe PAM module, nullok, rate limiting, code window.
- Ubuntu: Configure SSH to use two-factor authenticationOfficial Ubuntu tutorial.
- sshd_config(5)AuthenticationMethods, KbdInteractiveAuthentication, Match.
Related
- SSH keys and SSH server hardeningThe previous step: key-only login.
- Securing access step by stepThe chapter this guide is part of.
- Time synchronization2FA codes need the correct server time.
- Fail2BanBlocking repeated login attempts.
How to cite this publication (APA 7)Nepor, V. (2026, October 2). Two-Factor Authentication (2FA) via Google Authenticator on Ubuntu Server. Vrealmatic. https://vrealmatic.com/ubuntu/2fa-google-authenticator
Need a secure server setup?
We design, secure and document networks and servers.