Ubuntu server 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, it'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 by Google:
apt install libpam-google-authenticator
Then launch the authenticator and walk through the setup:

Do you want me to update your "/home/USER/.google_authenticator" file? (y/n)

  • y

Do you want to disallow multiple uses of the same authentication
token? This restricts you to one login about every 30s, but it increases
your chances to notice or even prevent man-in-the-middle attacks (y/n)

  • y

By default, a new token is generated every 30 seconds by the mobile app.
In order to compensate for possible time-skew between the client and the server,
we allow an extra token before and after the current time. This allows for a
time skew of up to 30 seconds between authentication server and client. If you
experience problems with poor time synchronization, you can increase the window
from its default size of 3 permitted codes (one previous code, the current
code, the next code) to 17 permitted codes (the 8 previous codes, the current
code, and the 8 next codes). This will permit for a time skew of up to 4 minutes
between client and server.
Do you want to do so? (y/n)

  • y

If the computer that you are logging into isn't hardened against brute-force
login attempts, you can enable rate-limiting for the authentication module.
By default, this limits attackers to no more than 3 login attempts every 30s.
Do you want to enable rate-limiting? (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 a GitLab Omnibus installation 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