DEV Community

kingyou
kingyou

Posted on

How to Enable Google Authenticator for SSH Login on Linux: Step-by-Step Guide

Introduction

Securing your SSH access is crucial for maintaining the integrity of your Linux server. While password authentication is common, it's vulnerable to brute-force attacks. Multi-Factor Authentication (MFA) using Google Authenticator adds an extra layer of security by requiring a time-based one-time password (TOTP) in addition to your regular credentials.

In this comprehensive guide, I'll walk you through setting up Google Authenticator for SSH login on your Linux server.

Prerequisites

Before we begin, make sure you have:

  • Root or sudo access to your Linux server
  • An active SSH connection to your server
  • A smartphone with Google Authenticator app installed (Android / iOS)
  • Basic knowledge of Linux command line

⚠️ Important Warning: Keep your current SSH session open throughout this process. Open a second terminal window for testing to avoid locking yourself out.


Step 1: Update Your System

First, ensure your system packages are up to date:

sudo apt update && sudo apt upgrade -y  # For Debian/Ubuntu
Enter fullscreen mode Exit fullscreen mode

For CentOS/RHEL/Fedora:

sudo yum update -y  # CentOS/RHEL 7
sudo dnf update -y  # CentOS/RHEL 8+ / Fedora
Enter fullscreen mode Exit fullscreen mode

Step 2: Install Google Authenticator PAM Module

Install the Google Authenticator PAM (Pluggable Authentication Module):

For Debian/Ubuntu:

sudo apt install libpam-google-authenticator -y
Enter fullscreen mode Exit fullscreen mode

For CentOS/RHEL/Fedora:

sudo yum install google-authenticator -y  # CentOS/RHEL 7
sudo dnf install google-authenticator -y  # CentOS/RHEL 8+ / Fedora
Enter fullscreen mode Exit fullscreen mode

You can verify the installation:

which google-authenticator
Enter fullscreen mode Exit fullscreen mode

This should return the path: /usr/bin/google-authenticator


Step 3: Configure Google Authenticator for Your User

Run the Google Authenticator setup for your user account:

google-authenticator
Enter fullscreen mode Exit fullscreen mode

You'll be asked several questions. Here are the recommended answers:

Question 1: Time-based tokens

Do you want authentication tokens to be time-based? (y/n)
Enter fullscreen mode Exit fullscreen mode

Answer: y (Yes - this enables TOTP)

After answering yes, you'll see:

  • A large QR code in your terminal
  • Your secret key
  • Verification code
  • Emergency scratch codes

📱 Scan the QR code with your Google Authenticator app, or manually enter the secret key if the QR code doesn't scan.

💾 Save the emergency scratch codes in a secure location! These are one-time use backup codes if you lose access to your phone.

Question 2: Update configuration file

Do you want me to update your "~/.google_authenticator" file? (y/n)
Enter fullscreen mode Exit fullscreen mode

Answer: y (This saves your configuration)

Question 3: Disallow multiple uses

Do you want to disallow multiple uses of the same authentication token? (y/n)
Enter fullscreen mode Exit fullscreen mode

Answer: y (Prevents replay attacks)

Question 4: Time skew

By default, tokens are good for 30 seconds. Do you want to increase the time window? (y/n)
Enter fullscreen mode Exit fullscreen mode

Answer: n (Keep the default 30-second window for better security)

Question 5: Rate limiting

Do you want to enable rate-limiting? (y/n)
Enter fullscreen mode Exit fullscreen mode

Answer: y (Protects against brute-force attacks - allows 3 login attempts per 30 seconds)


Step 4: Configure SSH to Use Google Authenticator

Now we need to configure PAM and SSH to use Google Authenticator.

4.1: Edit PAM Configuration

Open the PAM SSH configuration file:

sudo nano /etc/pam.d/sshd
Enter fullscreen mode Exit fullscreen mode

Add this line at the top of the file:

auth required pam_google_authenticator.so
Enter fullscreen mode Exit fullscreen mode

Optional but recommended: Comment out the common-auth line to disable password authentication and only use 2FA + SSH keys:

# @include common-auth
Enter fullscreen mode Exit fullscreen mode

Note: If you comment this out, you'll need SSH key authentication set up, otherwise you'll only need the 2FA code.

Save and exit (Ctrl+X, then Y, then Enter).

4.2: Configure SSH Daemon

Edit the SSH daemon configuration:

sudo nano /etc/ssh/sshd_config
Enter fullscreen mode Exit fullscreen mode

Find and modify these lines:

# Change this from 'no' to 'yes'
ChallengeResponseAuthentication yes
Enter fullscreen mode Exit fullscreen mode

For newer SSH versions (OpenSSH 9.x+), you might need:

KbdInteractiveAuthentication yes
Enter fullscreen mode Exit fullscreen mode

For even stronger security (2FA + SSH keys), add:

AuthenticationMethods publickey,keyboard-interactive
Enter fullscreen mode Exit fullscreen mode

This requires both SSH key authentication AND the 2FA code.

If you want 2FA or SSH key (either one), use:

AuthenticationMethods publickey keyboard-interactive
Enter fullscreen mode Exit fullscreen mode

Also ensure:

UsePAM yes
Enter fullscreen mode Exit fullscreen mode

Save and exit.


Step 5: Restart SSH Service

⚠️ Critical: Before restarting, ensure you have a backup session open!

Restart the SSH service:

For systems with systemd (Ubuntu 16.04+, CentOS 7+, Debian 8+):

sudo systemctl restart sshd
Enter fullscreen mode Exit fullscreen mode

For older systems:

sudo service ssh restart  # Debian/Ubuntu
sudo service sshd restart  # CentOS/RHEL
Enter fullscreen mode Exit fullscreen mode

Check the service status:

sudo systemctl status sshd
Enter fullscreen mode Exit fullscreen mode

Step 6: Test Your Configuration

Keep your existing SSH session open! Open a new terminal and try to connect:

ssh username@your-server-ip
Enter fullscreen mode Exit fullscreen mode

You should see prompts for:

  1. Your password (if not using SSH keys only)
  2. Verification code (from Google Authenticator app)

Enter the 6-digit code from your Google Authenticator app.

If successful, you'll be logged in! 🎉


Troubleshooting

Issue 1: Locked Out of Server

Prevention is key! Always keep a session open while configuring.

If locked out and you have console access (VPS panel, cloud provider console):

  1. Access via console
  2. Edit /etc/pam.d/sshd and comment out:
   # auth required pam_google_authenticator.so
Enter fullscreen mode Exit fullscreen mode
  1. Restart sshd: sudo systemctl restart sshd

Issue 2: "Invalid Verification Code" Error

Cause: Time synchronization issues.

Solution: Ensure your server's time is synchronized:

sudo timedatectl set-ntp true
sudo systemctl restart systemd-timesyncd
timedatectl status
Enter fullscreen mode Exit fullscreen mode

For older systems:

sudo ntpdate pool.ntp.org
Enter fullscreen mode Exit fullscreen mode

Issue 3: Emergency Access

If you lose your phone, use one of the emergency scratch codes you saved earlier. Each code can only be used once.

Issue 4: Multiple Users

Each user must run google-authenticator separately to set up their own 2FA. The configuration is stored per-user in ~/.google_authenticator.

Issue 5: SSH Keys Not Working

If you configured AuthenticationMethods publickey,keyboard-interactive and SSH keys aren't working:

  1. Verify your public key is in ~/.ssh/authorized_keys
  2. Check permissions:
   chmod 700 ~/.ssh
   chmod 600 ~/.ssh/authorized_keys
Enter fullscreen mode Exit fullscreen mode
  1. Check SSH logs:
   sudo tail -f /var/log/auth.log  # Debian/Ubuntu
   sudo tail -f /var/log/secure    # CentOS/RHEL
Enter fullscreen mode Exit fullscreen mode

Security Best Practices

  1. Save Emergency Codes Securely: Store scratch codes in a password manager or secure location
  2. Use Strong Passwords: Even with 2FA, maintain strong password practices
  3. Regular Backups: Back up your ~/.google_authenticator file securely
  4. Monitor Logs: Regularly check /var/log/auth.log for suspicious activity
  5. Combine with SSH Keys: Use both SSH keys and 2FA for maximum security
  6. Disable Root Login: In /etc/ssh/sshd_config, set PermitRootLogin no
  7. Change Default Port: Consider changing SSH from port 22 to reduce automated attacks
  8. Use Fail2Ban: Install fail2ban to automatically block repeated failed login attempts

Useful Commands

Regenerate 2FA for current user:

google-authenticator -f
Enter fullscreen mode Exit fullscreen mode

View your configuration:

cat ~/.google_authenticator
Enter fullscreen mode Exit fullscreen mode

Disable 2FA temporarily (for current user):

mv ~/.google_authenticator ~/.google_authenticator.backup
Enter fullscreen mode Exit fullscreen mode

Re-enable:

mv ~/.google_authenticator.backup ~/.google_authenticator
Enter fullscreen mode Exit fullscreen mode

Check SSH authentication logs:

sudo grep sshd /var/log/auth.log | tail -20
Enter fullscreen mode Exit fullscreen mode

Conclusion

Congratulations! You've successfully set up Google Authenticator for SSH on your Linux server. Your server is now protected by two-factor authentication, significantly reducing the risk of unauthorized access.

Key Takeaways:

  • Always test in a separate terminal before closing your original session
  • Save emergency scratch codes in a secure location
  • Keep your server's time synchronized
  • Consider combining 2FA with SSH key authentication for maximum security

Remember, security is an ongoing process. Regularly review your server logs, keep your system updated, and follow security best practices.

Have questions or run into issues? Drop a comment below, and I'll be happy to help! 👇


Did this guide help you? Give it a ❤️ and share it with others who might find it useful!

Top comments (0)