Google’s SSH two-factor authentication (2FA) service, known as Google Authenticator SSH, improves SSH (Secure Shell) access security by adding a second layer of authentication. While SSH already provides a secure way to establish an encrypted connection to a remote server, integrating 2FA increases 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’ll 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 VPS. Run the following command:
sudo apt install libpam-google-authenticator
You’ll then be prompted to confirm the installation by entering "Y". Type it, press Enter, and Google Authenticator will be installed!
Start Google Authenticator by entering google-authenticator. Make sure your window is large enough to display the QR code. Otherwise, press "CTRL+C" and run the command again.
You’ll be asked again whether you want to continue — type "Y" to confirm. A QR code will now appear. Open the authenticator app on your smartphone and scan the QR code. For this example, we’re using Google Authenticator:
Be sure to copy the backup codes. You can use each one once if you lose access to your authenticator.
The app will now display the codes you’ll need to log in later. Here’s what they look like:
Next, you’ll 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 period during which a code is valid be extended?
- Should only three logins be allowed every 30 seconds? (Protection against brute-force attacks)
For security reasons, we recommend answering "Yes" to all the questions.
Now we need to configure Google Authenticator so that it’s actually used. This requires two changes.
Enable the required modules in the /etc/ssh/sshd_config file. Open the file with:
sudo nano /etc/ssh/sshd_config
You’re now in the text editor. Use the arrow keys to move around, delete text, or enter new text. Save the file by pressing 'CTRL + X', then 'Y', and pressing Enter.
Make sure the UsePAM and ChallengeResponseAuthentication lines 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 we’ll add Google Authenticator to the login process in the /etc/pam.d/sshd file. 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 by pressing 'CTRL + X', then 'Y', and pressing Enter.
It’s now time to log in with 2FA for the first time. Once you’ve followed the steps above, you just need to restart your SSH connection.
Enter your password as usual. You’ll then be asked for a code — simply enter your current 2FA code.
And you’re logged in!