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-authenticatorAlmaLinux / 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-authenticator2. 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:| Question | Answer | Purpose |
|---|---|---|
| Do you want authentication tokens to be time-based? | y | Use time-based TOTP codes |
| Do you want to update your "~/.google_authenticator" file? | y | Save the secret key |
| Do you want to disallow multiple uses of the same authentication token? | y | Prevent codes from being reused |
| Do you want to increase the time skew window? | n | Keep the default time window |
| Do you want to enable rate-limiting? | y | Limit the number of code verification attempts |
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.
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_authenticatorRestrict 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.soIf 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 nullokThis 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-authDo 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 yesIn 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.
PubkeyAuthentication yes
KbdInteractiveAuthentication yes
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 yesWith this method, the user's password is not requested when logging in via SSH.
PasswordAuthentication no
KbdInteractiveAuthentication yes
UsePAM yes
AuthenticationMethods publickey,keyboard-interactive
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 noIn 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.
PasswordAuthentication no
KbdInteractiveAuthentication yes
UsePAM yes
AuthenticationMethods keyboard-interactive
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 sshd5. 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 deployThe Match block should be placed at the end of /etc/ssh/sshd_config to prevent subsequent global directives from accidentally falling within its scope.
AuthenticationMethods publickey
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: yesIf 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 yesMake sure the following module is included in /etc/pam.d/sshd:
KbdInteractiveAuthentication yes
auth required pam_google_authenticator.soCheck 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-authThis 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_authenticatorViewing the SSH Log
Use the following commands to diagnose authentication errors.Ubuntu / Debian:
journalctl -u ssh -n 50AlmaLinux / Rocky Linux:journalctl -u sshd -n 508. How to Disable 2FA
To disable two-factor authentication, you need to restore the previous PAM and SSH settings.- Open /etc/pam.d/sshd and remove or comment out the following line:
auth required pam_google_authenticator.so
- If you modified the default PAM configuration, restore its original state.
- In /etc/ssh/sshd_config, remove or modify the AuthenticationMethods parameter to restore the required authentication method.
- Check the configuration:
sshd -t - Restart the SSH service.
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.