Configuring 2FA for SSH with Google Authenticator

10 Nov 2026, 15:24:28
Two-factor authentication (2FA) provides additional protection for SSH connections using a one-time password (TOTP) generated by an application on your phone.
Even if an attacker obtains your password or SSH key, an additional code will still be required to log in. You can use Google Authenticator, Aegis, 2FAS, Authy, or any other application that supports TOTP.
Let's look at how to configure two-factor authentication on Ubuntu, Debian, AlmaLinux, and Rocky Linux.
Before starting the configuration, open a second SSH session to the server and keep it open until the verification is complete. Errors in the PAM or SSH configuration may result in losing SSH access. If you cannot connect to the server after changing the settings, our VPS servers provide access to a VNC console, which you can use to connect to the server and fix the configuration.

1. Installing the Required Packages

To use 2FA, you need to install the Google Authenticator PAM module.
Ubuntu / Debian:
apt update
apt install libpam-google-authenticator
AlmaLinux / Rocky Linux:
First, enable the EPEL repository if it is not already installed:
dnf install epel-releaseThen install the package:
dnf install google-authenticatorDepending on the distribution version and enabled repositories, the package name may differ. If the package cannot be found, check its availability:
dnf search google-authenticator

2. Generating a Secret Key for a User

A separate secret key must be generated for each user who needs 2FA enabled.
Run the command as the corresponding user, not as root:
google-authenticatorDuring the setup process, you will be prompted to answer several questions:
QuestionAnswerPurpose
Do you want authentication tokens to be time-based?yUse time-based TOTP codes
Do you want to update your "~/.google_authenticator" file?ySave the secret key
Do you want to disallow multiple uses of the same authentication token?yPrevent codes from being reused
Do you want to increase the time skew window?nKeep the default time window
Do you want to enable rate-limiting?yLimit the number of code verification attempts
Alternatively, you can perform the configuration with a single command without answering interactive prompts:
google-authenticator -t -d -f -r 3 -R 30 -w 3Command parameters:
  • -t — use time-based TOTP codes.
  • -d — disallow reuse of authentication codes.
  • -f — save the settings without additional confirmation.
  • -r 3 — allow no more than three attempts.
  • -R 30 — set the rate-limiting interval to 30 seconds.
  • -w 3 — accept codes within an extended time window.
After running the command, a QR code, secret key, and emergency recovery codes will be displayed.
Scan the QR code using an authentication application on your phone. Store the recovery codes in a safe place, such as a password manager. Each recovery code can only be used once to restore access.
The secret key is stored in the following file:
~/.google_authenticator
Restrict access to this file:
chmod 400 ~/.google_authenticatorThe file must be owned by the user for whom the secret key was generated.

3. Configuring PAM

PAM (Pluggable Authentication Modules) handles the verification of additional authentication factors.
Open the SSH configuration file:
nano /etc/pam.d/sshdOn Ubuntu and Debian, add the following line:
auth required pam_google_authenticator.so
If you are enabling 2FA gradually and not all users have generated their secret keys yet, you can temporarily use the nullok parameter:
auth required pam_google_authenticator.so nullok
This allows users without a ~/.google_authenticator file to log in without the second authentication factor. Once 2FA has been configured for all users, make sure to remove nullok.
AlmaLinux / Rocky Linux specifics
On these distributions, PAM usually uses the password-auth stack through the following directive:
auth substack password-auth
Do not remove or comment out this line without first reviewing the existing configuration. It may contain additional password verification and account protection mechanisms.
Adding Google Authenticator to PAM on AlmaLinux and Rocky Linux must be done while taking the existing authentication stack into account. Do not replace the default PAM configuration with a simplified setup unless absolutely necessary.
Important: for the SSH key + TOTP authentication method, password authentication must be disabled at the SSH level, and PAM must correctly handle the interactive request for the second authentication factor. Do not disable password verification in PAM by simply removing the entire default authentication stack.

4. Configuring SSH

Open the SSH configuration file:
nano /etc/ssh/sshd_configMake sure the following parameters are specified:
UsePAM yes
PubkeyAuthentication yes
KbdInteractiveAuthentication yes
In OpenSSH versions earlier than 8.7, the ChallengeResponseAuthentication directive was used for interactive authentication. Newer versions use KbdInteractiveAuthentication. The old name is retained as a deprecated alias.
Next, choose one of the authentication methods below:

Option A. SSH Key + TOTP Code (Recommended)

This method provides additional protection: the SSH key is verified first, followed by a request for a one-time code.
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication yes
UsePAM yes
AuthenticationMethods publickey,keyboard-interactive
With this method, the user's password is not requested when logging in via SSH.

Option B. Password + TOTP Code

If you want to use a regular password instead of an SSH key, you can configure the following authentication method:
PubkeyAuthentication no
PasswordAuthentication no
KbdInteractiveAuthentication yes
UsePAM yes
AuthenticationMethods keyboard-interactive
In this case, the password and one-time code are verified through PAM. To make this work, PAM must be configured to request both authentication factors.
This method is less preferable than SSH key + TOTP.

Verifying the Final Configuration

On modern Ubuntu and Debian systems, additional SSH settings may be located in the /etc/ssh/sshd_config.d/ directory. These files can affect the effective configuration.
Check the effective parameters:
sshd -T | grep -Ei 'authenticationmethods|passwordauthentication|kbdinteractiveauthentication|usepam'If Match blocks are used, check the configuration for a specific user with:
sshd -T -C user=deploy,host=localhost,addr=127.0.0.1 | grep -Ei 'authenticationmethods|passwordauthentication|kbdinteractiveauthentication|usepam'Before restarting SSH, always check the configuration:
sshd -tIf there are no errors, restart the service.
Ubuntu / Debian:
systemctl restart sshAlmaLinux / Rocky Linux:
systemctl restart sshd

5. Testing the Connection

Do not close your current SSH session until the verification is complete.
Open a new terminal window and try connecting to the server:
ssh user@serverWhen using an SSH key and a TOTP code, the key will be verified first, followed by a prompt for the one-time code.
Enter the six-digit code from Google Authenticator or another TOTP application.
If the connection is successful, the configuration is working correctly.
If authentication fails, return to your open SSH session and check the PAM and SSH settings.

6. Exceptions for Service Accounts

Some service accounts are used for automation tasks such as deployment, backups, CI/CD, and other operations.
These connections cannot enter a one-time code manually. You can configure separate rules for them using a Match User block.
For example, you can allow the deploy user to authenticate only with an SSH key:
Match User deploy
    AuthenticationMethods publickey
The Match block should be placed at the end of /etc/ssh/sshd_config to prevent subsequent global directives from accidentally falling within its scope.
For additional protection, it is recommended to restrict the service account's permissions and use SSH key restrictions in ~/.ssh/authorized_keys, such as from= or command=.
After changing the configuration, check it:
sshd -tThen restart the SSH service.

7. Common Issues

The Code Is Not Accepted

The most common cause is a time synchronization mismatch between the server and the phone.
Check the synchronization status:
timedatectlPay attention to the following parameter:
System clock synchronized: yes
If time synchronization is not working, configure the appropriate service.
Ubuntu / Debian with chrony:
systemctl enable --now chronyAlmaLinux / Rocky Linux:
systemctl enable --now chronydIf systemd-timesyncd is being used, check its status:
systemctl status systemd-timesyncdAlso, make sure automatic time synchronization is enabled on your phone.

The Code Is Not Requested

Check the following parameters in /etc/ssh/sshd_config:
UsePAM yes
KbdInteractiveAuthentication yes
Make sure the following module is included in /etc/pam.d/sshd:
auth required pam_google_authenticator.so
Check the effective SSH configuration using sshd -T.

Both a Password and a Code Are Requested When Logging In with an SSH Key

Check the PAM settings. On Ubuntu and Debian, the default configuration may contain the following line:
@include common-auth
This directive is responsible for additional system password verification. If you want to use SSH key + TOTP authentication without a password, PAM must be configured accordingly while preserving the correct verification of the second authentication factor.
Do not remove the entire default authentication stack without first checking its contents.

The ~/.google_authenticator File Cannot Be Found

Make sure the user ran the google-authenticator command under their own account.
Check whether the file exists:
ls -la ~/.google_authenticatorIf the nullok parameter is used, a user without this file will be able to log in without the second authentication factor. Without nullok, the absence of this file will result in authentication being denied.

SELinux Issues on AlmaLinux / Rocky Linux

If 2FA is not working while SELinux is enabled, check for error messages:
ausearch -m avc -ts recentAlso, check the SSH log:
journalctl -u sshd -n 50If necessary, restore the default SELinux contexts for the home directory:
restorecon -v ~/.google_authenticator

Viewing the SSH Log

Use the following commands to diagnose authentication errors.
Ubuntu / Debian:
journalctl -u ssh -n 50AlmaLinux / Rocky Linux:
journalctl -u sshd -n 50

8. How to Disable 2FA

To disable two-factor authentication, you need to restore the previous PAM and SSH settings.
  1. Open /etc/pam.d/sshd and remove or comment out the following line:
    auth required pam_google_authenticator.so
  2. If you modified the default PAM configuration, restore its original state.
  3. In /etc/ssh/sshd_config, remove or modify the AuthenticationMethods parameter to restore the required authentication method.
  4. Check the configuration:
    sshd -t
  5. Restart the SSH service.
To disable 2FA for a specific user only, you can delete their secret key file:
rm ~/.google_authenticatorHowever, this will only work if the nullok parameter is used in PAM. Otherwise, the user will lose the ability to log in via SSH.

Conclusion

Two-factor authentication significantly improves the security of SSH connections and protects your server against unauthorized access.
Key recommendations:
  • Use SSH key + TOTP code authentication instead of regular password-based authentication.
  • Generate a separate secret key for each user.
  • Store emergency recovery codes in a safe place.
  • Keep the server and phone clocks synchronized.
  • Do not close your current SSH session until the new connection has been successfully tested.
  • Use separate Match User rules and restricted SSH keys for service accounts.
Before enabling 2FA on a production server, it is recommended to test the configuration with a separate user account first.