Two-factors authentication with OpenSSH

TL;DR

I figured that two-factors authentications can be enabled in OpenSSH.

Like most of the things that I figure out, it was no secret around and I found plenty of tutorials and how-to-s once I managed to articulate my need to a search engine.

One useful guide I found is this article in Linode, which has to be followed with a grain of salt though, especially if we want to stick with public key authentication and the TOTP-based second factor. The things in the page are correct, but the instructions for the public-key part assume that the configuration for plain password authentication were already done too, which might not be the case if we’re aiming for key or certificate-based login as the first factor.

Anyway.

First, install google-authentication, which in Debian boils down to:

apt update
# optionally... apt upgrade
apt install google-authenticator

The google-authenticator program should be run and the page in Linode does an excellent job at describing the steps and providing suggested values.

Then we have the configuration part. In the Pluggable Authentication Modules configuration for sshd, available at /etc/pam.d/sshd we must disable plain password authentication and add the google-authenticator:

# around the beginning of the file, comment the following line if not
# already commented out:
# @include common-auth

# ---

# then, around the bottom, *add* the following if not already there:
auth    required      pam_google_authenticator.so

NOTE before messing up with sshd_config it’s hightly suggested to have a second connection to the target, in order to correct errors in case of failures.

OK, so now every time PAM is used by sshd we should pass through google_authenticator. Still, we have to say this to sshd, so in /etc/ssh/sshd_config:

ChallengeResponseAuthentication yes
UsePAM yes
AuthenticationMethods publickey,keyboard-interactive

We already saw the AuthenticationMethods… comma! This here means first require public key authentication, and after is succeeds use whatever is fine with PAM (that is, google-authenticator).

After restring the daemon things should be set up:

# first make sure that everything's fine with sshd_config
sshd -t

# then...
sudo systemctl reload ssh

Last, it’s possible to restrict this to users or groups only, it will be sufficient to move the AuthenticationMethods configuration in an ad-hoc section of /etc/ssh/sshd_config:

# plain users are OK with public-key authentication only
AuthenticationMethods publickey

# others... need a bit more kick
Match User foobar
    AuthenticationMethods publickey,keyboard-interactive

And after this… stay safe, folks!


Comments? Octodon, , GitHub, Reddit, or drop me a line!