Two-Factor Authentication (2FA) is one of the biggest additions to the security shield for your Linux server. It does that by requiring a secondary method of authentication after entering the correct SSH password. On Ubuntu and RHEL (Red Hat Enterprise Linux), you can easily enable 2FA using Google Authenticator or libpam-google-authenticator.
This guide will show you how to implement 2FA for SSH on both systems.
Google Authenticator is a PAM (Pluggable Authentication Module) that generates Time-based One-Time Passwords (TOTP).
Ubuntu
sudo apt update
sudo apt install libpam-google-authenticator
RHEL
sudo yum update
sudo yum install epel-release
sudo yum install google-authenticator
1. Run the following command for the user you want to secure with 2FA:
google-authenticator
2. You will be prompted with a series of questions. Answer as follows:
Do you want authentication tokens to be time-based? y
Do you want me to update your .google_authenticator file? y
Do you want to disallow multiple uses of the same authentication token? y
Do you want to increase the time window? n
Do you want to enable rate-limiting? y
3. A QR code and a secret key will be generated.
You need to modify the PAM SSH configuration to use Google Authenticator.
1. Open the PAM configuration file for SSH:
sudo nano /etc/pam.d/sshd
2. Add the following line to the top:
auth required pam_google_authenticator.so
You now need to modify the SSH configuration to enforce 2FA.
1. Open the SSH configuration file:
sudo nano /etc/ssh/sshd_config
2. Find and modify the following settings:
ChallengeResponseAuthentication yes
PasswordAuthentication yes
UsePAM yes
3. Add or modify the AuthenticationMethods directive to ensure both password and 2FA are required:
AuthenticationMethods publickey,password publickey,keyboard-interactive
To apply the changes, restart the SSH daemon:
sudo systemctl restart sshd
1. Open a new terminal and SSH into your server:
ssh your-username@your-server-ip
2. You should be prompted to enter your password and then a verification code from Google Authenticator.
To limit 2FA to specific users, modify /etc/pam.d/sshd and add the following line before pam_google_authenticator:
auth [success=1 default=ignore] pam_succeed_if.so user in user1:user2
Replace user1 and user2 with the usernames that should use 2FA.
sudo tail -f /var/log/auth.log # Ubuntu
sudo tail -f /var/log/secure # RHEL