This page looks best with JavaScript enabled

Setting up 2FA for SSH server

 ·  ☕ 2 min read

2FA (two-factor authentication) is a method of confirming a user’s claimed identity by utilizing something they know (password) and a second factor other than something they have or something they are. An example of a second step is the user repeating back something that was sent to them through an out-of-band mechanism. Or, the second step might be a six digit number generated by an app that is common to the user and the authentication system.
So… Let’s configure our OpenSSH server with 2FA!

SSH installation

If you haven’t already installed and configured SSH, here’s how to do it.

  1. Install OpenSSH server:
    sudo apt-get install openssh-server 
  2. Enable and start daemon:
    sudo systemctl enable sshd
    sudo systemctl start sshd

PAM installation

PAM (Pluggable Authentication Module) is an authentication infrastructure used on GNU/Linux systems to authenticate a user.
The PAM, that we will use, is made by Google. Let’s install and configure it.

  1. Install Google’s PAM:

    sudo apt-get install libpam-google-authenticator
  2. Generate a TOTP key for the user you want to add a second factor to:


Note: the key is generated for specific user, not system wide. This means every user that wants to use a TOTP authenticator application will need to log in and run google-authenticator to get their own key.

PAM configuration

  1. Open up PAM configuration file for sshd for editing using nano or your favorite text editor:
    sudo nano /etc/pam.d/sshd
  2. Add the following line to enable Google’s PAM lib:
    auth required
  3. Comment out common-auth if you don’t want to be asked for UNIX user password:
    # Standard Un*x authentication.
    # @include common-auth

OpenSSH configuation

The next step now is to configure SSH to use your TOTP key. We’ll need to tell SSH about the PAM and then configure SSH to use it.

  1. Open up OpenSSH configuration file for editing using nano or your favorite text editor:
    sudo nano /etc/ssh/sshd_config
  2. Look for ChallengeResponseAuthentication option and change its value to yes:
    ChallengeResponseAuthentication yes
  3. Uncomment PasswordAuthentication line and change its value to no to tell SSH not to prompt for a password:
    # Change to no to disable tunnelled clear text passwords
    PasswordAuthentication no
  4. Add following lines to configuration file:
    UsePAM yes
    AuthenticationMethods publickey,keyboard-interactive

Done! You configured 2FA for OpenSSH. Now you’ll be asked for TOTP key on every connect.

What's on this Page