How to Set Up Two-Factor Authentication with Google Authenticator for SSH

Using SSH with Google Authenticator can greatly enhance the security of your server by adding an additional layer of authentication. Follow the steps below to implement Google Authenticator on Red Hat, CentOS, and Ubuntu Linux distributions.

Note: Before proceeding, ensure that you have appropriate access permissions and consult with your administration teams to avoid unintended access issues.

  1. Install the Google Authenticator module by executing the following commands:

    For Red Hat and CentOS:

    yum install google-authenticator
    

    For Ubuntu and Debian:

    apt install libpam-google-authenticator
    

    If you are unable to find the google-authenticator package, seek assistance to locate it.

  2. Open the /etc/pam.d/sshd file and add the following line at the end of the auth section:

    auth required pam_google_authenticator.so
    
  3. Open the /etc/ssh/sshd_config file and change ChallengeResponseAuthentication no to ChallengeResponseAuthentication yes.

  4. Restart the SSH service by executing the following command:

    For Red Hat and CentOS:

    systemctl restart sshd
    

    For Ubuntu and Debian:

    systemctl restart sshd
    

Setting up keys for the user

Follow these steps to set up keys for the user:

  1. Run the following command:

    google-authenticator
    
  2. Answer yes when prompted to update your ~/.google_authenticator file and provide responses to the following three prompts.

  3. After completing the steps, you will see the following information:

    • New secret key
    • Verification code
    • Emergency scratch codes

    Use the new secret key to add the account to your Google Authenticator app on your phone. Safely store the emergency scratch codes in case you lose your phone or need to log in without the app.

Now, when logging in to your server with your user account, you will be prompted to enter the Google authentication token along with your regular password. Accounts that have not been set up with Google Authenticator will not be permitted to log in.

Here’s an example of the login process:

$ ssh root@example.com
Verification code:

root@example:~#

By implementing Google Authenticator, you have significantly strengthened the security of your SSH access. Enjoy the added protection and peace of mind knowing that only authorized users can successfully log in to your server.