Google Authenticator is a software-based authenticator by Google that implements two-step verification services using the Time-based One-time Password Algorithm and HMAC-based One-time Password algorithm for authenticating users of software applications. So, TOTP can substantially improve SSH login security.

Install PAM Module

Login into Ubuntu 20.04 VPS through SSH, then use the following command to install the Google Authenticator PAM module:

sudo apt install libpam-google-authenticator

Generate Your 2FA Code

Run the Google Authenticator setup program. You can run the program without command-line options for an interactive setup, or use the following options:

google-authenticator -t -f -d -w 3 -e 5 -r 3 -R 15

These options explained:

  • -t : Use TOTP verification
  • -f : Write the configuration to ~/.google_authenticator
  • -d : Do not allow reuse of previously used tokens.
  • -w 3 : The window size of allowed tokens. By default, tokens expire every 30 seconds. A window size of 3 allows authentication with the token before and after the current token for clock skew.
  • -e 5 : Generate 5 emergency backup codes
  • -r 3 -R 15 : Rate-limit. Allow 3 logins every 30 seconds.

Use --help for more options.

The program will update your configuration files and display several values:

  • A QR code. You can scan this code with most authenticator apps.
  • A secret key. Enter this key in your app if you cannot scan the QR code.
  • The initial verification code, which will expire in 30 seconds.
  • A list of 5 one-time use emergency codes.

Configure SSH

Edit your SSH PAM configuration file:

nano /etc/pam.d/sshd

Add the following line to the bottom of the file.

# Google TOTP
Auth required pam_google_authenticator.so nullok
The nullok option allows users that have not yet generated a 2FA code to log in, while codes are required if the user has followed Step 2 above. This option is useful during rollout. After all users have generated codes, you can remove the nullok option to require 2FA for everyone.

Save and close the file.

Edit the SSH daemon configuration file:

nano /etc/ssh/sshd_config

Find the line for ChallengeResponseAuthentication and set its value to yes.

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication yes

Save and close the file.

Restart the SSH service daemon.

Attention: Do NOT terminate the current SSH connection, or you may not be able to connect to your server if you configured it wrong.
systemctl restart sshd.service

Related Post:

References:

TOC