How to Set Up Two-Factor Authentication (2FA) for VPS Access

Securing your VPS with Two-Factor Authentication (2FA) adds an additional layer of security by requiring a second form of verification along with your password. This guide explains how to enable and configure 2FA for your VPS access.


Step 1: Install Google Authenticator or Any OTP App

To use 2FA, you will need an application like Google Authenticator or Authy installed on your mobile device.

  • Download and install Google Authenticator from the Google Play Store or Apple App Store.
  • Alternatively, use any OTP (One-Time Password) app compatible with 2FA.

Step 2: Install 2FA on Your VPS

Install the required package for 2FA on your VPS.

  • For Debian-based systems:
    sudo apt update  
    sudo apt install libpam-google-authenticator  
    
  • For RHEL-based systems:
    sudo yum install epel-release  
    sudo yum install google-authenticator  
    

Step 3: Configure 2FA for Your SSH Access

Modify the SSH and PAM configuration to enable 2FA.

  • Open the PAM configuration file:

    sudo nano /etc/pam.d/sshd  
    
    • Add the following line at the top:
      auth required pam_google_authenticator.so  
      
    • Save and exit the file.
  • Update the SSH configuration file:

    sudo nano /etc/ssh/sshd_config  
    
    • Find the line:
      ChallengeResponseAuthentication  
      
    • Set it to:
      ChallengeResponseAuthentication yes  
      
    • Save and exit the file.
  • Restart the SSH service:

    sudo systemctl restart sshd  
    

Step 4: Set Up Google Authenticator for Your User

  • Run the Google Authenticator setup command:

    google-authenticator  
    
  • Answer the setup prompts:

    • Confirm time-based tokens by typing y.
    • A QR code and secret key will be displayed.
  • Scan the QR code with your 2FA app or manually enter the key.

  • Save the emergency codes provided for recovery.


Step 5: Test 2FA Authentication

  • Open a new SSH session and log in to your VPS.
  • Enter your password as usual.
  • Enter the 6-digit code from your 2FA app when prompted.
  • If successful, you will access your VPS.

Step 6: Enable 2FA for Additional Users (Optional)

Repeat Step 4 for each user account you want to secure with 2FA.


Step 7: Troubleshooting and Tips

  • If you lose access to your 2FA app, use the recovery codes generated during setup to log in.
  • Ensure your server's time is synchronized to avoid token mismatches:
    sudo apt install ntp     # For Debian-based  
    sudo yum install ntp     # For RHEL-based  
    sudo systemctl enable ntpd  
    sudo systemctl start ntpd  
    

With 2FA enabled, your VPS will have stronger protection against unauthorized access, giving you enhanced security and peace of mind.

Was this answer helpful? 0 Users Found This Useful (0 Votes)