Updated: 28 September 2026 · Applies to: Ubuntu 24.04, AlmaLinux 9 and Rocky Linux 9
Two-factor authentication (2FA) adds a one-time code from an authenticator app to your SSH login. This guide combines it with SSH keys, so a login needs your key and a code. It is for Ubuntu 24.04 and AlmaLinux 9 / Rocky Linux 9.
Note: Keep your current SSH session open until you have tested a new login in a second window. On a Ucartz VPS you can also use the VNC console if you lock yourself out.
1. Install the PAM module
apt install libpam-google-authenticator # Ubuntu / Debian dnf install epel-release && dnf install google-authenticator # AlmaLinux / Rocky
2. Create the secret for your user
Run google-authenticator as the user who logs in (not with sudo). Answer y for time-based tokens, scan the QR code with an authenticator app, and store the emergency codes safely. Answer y to the remaining questions for the recommended settings.
On AlmaLinux/Rocky, SELinux does not let SSH read the file in your home folder. Move it into ~/.ssh: mv ~/.google_authenticator ~/.ssh/ && restorecon -Rv ~/.ssh.
3. Configure PAM
Add this line at the end of /etc/pam.d/sshd:
auth required pam_google_authenticator.so # Ubuntu / Debian
auth required pam_google_authenticator.so secret=/home/${USER}/.ssh/.google_authenticator # AlmaLinux / Rocky
So that SSH asks for the code but not the password, comment out @include common-auth (Ubuntu/Debian) or auth substack password-auth (AlmaLinux/Rocky) in the same file.
4. Configure SSH
Create /etc/ssh/sshd_config.d/10-2fa.conf:
KbdInteractiveAuthentication yes UsePAM yes AuthenticationMethods publickey,keyboard-interactive
Check and restart: sshd -t && systemctl restart ssh (sshd on AlmaLinux/Rocky).
5. Test
In a new terminal, log in. You are asked for Verification code after the key is accepted. Only close your old session when this works.
Tip: Users without a .google_authenticator file cannot log in once this is active. To roll out gradually, add nullok to the PAM line until every user has set it up.