The SSH two-factor authentication service from Google, known as Google Authenticator SSH, increases the security of SSH (Secure Shell) access by adding a second layer of authentication. While SSH already provides a secure method to establish an encrypted connection to a remote server, integrating 2FA enhances security by requiring users to enter not only their password but also a one-time verification code generated by Google Authenticator. In this guide, we will show you how to install and configure the Google Authenticator SSH service on a Linux server.
First, you need to install Google Authenticator on your Linux server. Run the following command:
sudo apt install libpam-google-authenticator
You will then be prompted to confirm the installation by typing "Y". Enter it and press Enter to install Google Authenticator!
Start Google Authenticator by typing google-authenticator. Make sure your window is large enough to display the QR code; otherwise, press "CTRL+C" and run the command again.
You will be asked again if you want to proceed – type "Y" to confirm. Now a QR code will be displayed. Open your authenticator app on your smartphone and scan the QR code. For this example, we use Google Authenticator:
Be sure to copy the backup codes; you can use each once if you lose access to your authenticator.
The app will now show you the codes you will need to log in later. It looks like this:
Next, you will be asked a few questions:
- Do you want to save the Google Authenticator configuration?
- Do you want to allow only one login every 30 seconds?
- Should the time window for a code be extended?
- Should only three logins be allowed every 30 seconds? (Protection against brute force)
For security reasons, we recommend answering "Yes" to all questions.
Now we need to configure Google Authenticator so that it is actually used. Two adjustments are necessary.
Enable the required modules in the file /etc/ssh/sshd_config. Open the file with:
sudo nano /etc/ssh/sshd_config
You are now in a text editor. Use the arrow keys to navigate, delete, or add text. Save the file with CTRL + X, then Y and press Enter.
Make sure the two lines UsePAM and ChallengeResponseAuthentication are set to yes. It should look like this:
Save the file as described and restart SSH with the following command:
sudo systemctl restart ssh
Now add Google Authenticator to the login process in the file /etc/pam.d/sshd. Open the file with:
sudo nano /etc/pam.d/sshd
Scroll to the end of the file and add the following line:
auth required pam_google_authenticator.so
Save the file again with CTRL + X, then Y and Enter.
Now it’s time to log in with 2FA for the first time. After following the steps above, simply restart your SSH connection.
Enter your password as usual. Then you will be asked for a code – just enter the current 2FA code.
And you’re logged in!