Skip to content

Enabling Two-Factor Authentication for SSH

Two-factor authentication (2FA) adds an extra layer of protection to your server by requiring not only your username and password but also a time-based one-time code generated on your mobile device. This makes brute-force attacks and unauthorized access much more difficult.

By default, SSH logins require only a username and password. With 2FA enabled, you’ll also need a temporary numeric code generated by an authenticator app (such as Google Authenticator or Authy). This ensures that even if your password is compromised, attackers cannot log in without your mobile device.

  • Root access to your server.
  • SSH access enabled.
  • An authenticator app installed on your smartphone (Google Authenticator, Authy, Microsoft Authenticator, etc.).

For best security, disable direct root logins and create a normal user account with sudo privileges. (See our article on Disabling SSH logins for the root account for details.)

Step 2: Install Google Authenticator on the Server

Section titled “Step 2: Install Google Authenticator on the Server”

Log in to your server via SSH as root and install the required package:

  • Debian/Ubuntu:

    Terminal window
    apt-get install libpam-google-authenticator
  • AlmaLinux/Fedora:

    Terminal window
    yum install google-authenticator
  1. While logged in as your non-root user, run:

    Terminal window
    yum install google-authenticator
  2. Answer the prompts:

    • Time-based tokens? → y
    • Update .google_authenticator file? → y
    • Disallow multiple uses of the same token? → y
    • Increase token validity window? → n (default is more secure)
    • Enable rate-limiting? → y
  3. A QR code and secret key will be displayed.

    • Scan the QR code with your authenticator app.
    • Save the emergency backup codes in a safe place.
  1. Edit the PAM SSH file:

    Terminal window
    nano /etc/pam.d/sshd

    Add this line at the top:

    Terminal window
    auth required pam_google_authenticator.so nullok
  2. Edit the SSH configuration file:

    nano /etc/ssh/sshd_config

    Find and change:

    ChallengeResponseAuthentication yes
  3. Restart SSH:

    • Debian/Ubuntu:

      Terminal window
      service ssh restart
    • AlmaLinux/Fedora:

      Terminal window
      service sshd restart
  • Open a new terminal and log in as your non-root user.

  • You should be prompted for:

    1. Verification code (from your authenticator app).
    2. Password (your user password).

Do not close your root session until you confirm the new login works.

If you need to disable 2FA:

  1. Remove or comment out the pam_google_authenticator.so line in /etc/pam.d/sshd.
  2. Set ChallengeResponseAuthentication no in /etc/ssh/sshd_config.
  3. Restart the SSH service.