UbuntuServer PAM authentication with PrivateKey & Google Authenticator

As I started using pageant to handle my SSH key management and automate SSH logins I saved a few seconds for each login. So I thought, "Why not spend those saved seconds on an extra layer of security?". The simplest option was the Google Authenticator. Once installed on your phone (Android/iOS) you can create a QR-Code on your server (output in the terminal, pretty cool idea if you ask me) and link it to your phone. Using this setup, anyone who wants to access your server will need the private key's password (if pageant is not running) and your phone. But! he needs the phone at that moment(!) because the code keeps changing every 30 sec (by default).

If you like the Idea, let's get started by installing the PAM authentication module from google:
apt install libpam-google-authenticator
Then launch the authenticator and walk through the setup:

  • y
  • y
  • y
  • n
  • y

and scan the resulting QR-Code with your phone.

Now we need to enable this module for PAM:
nano /etc/pam.d/sshd

# Standard Un*x authentication.
#@include common-auth

# Standard Un*x password updating.
@include common-password
auth required pam_google_authenticator.so nullok

and for SSH:
nano /etc/ssh/sshd_config

ChallengeResponseAuthentication yes
UsePAM yes
AuthenticationMethods publickey,keyboard-interactive

Optional: If you have GitLab running on the same machine, you will need to set the authentication methods for the 'git' user to 'publickey' like this:

Match User git
    AuthenticationMethods publickey

Finally restart the SSH service using: systemctl restart sshd