Jun 5, 2017

How To Set Up Multi-Factor Authentication for SSH on Ubuntu

The following tested on Ubuntu on Microsoft Azure. It is not working for Ubuntu on Google cloud VM. You won't be able to ssh from browser any more. And using gcloud you still can ssh into the server without MFA code.

To enable it for GUI login, edit /etc/pam.d/common-auth:

sudo nano /etc/pam.d/common-auth
and add this 
auth required pam_google_authenticator.so 
above the line 
auth    [success=1 default=ignore]      pam_unix.so nullok_secure 
then save the file.

1. Install and configure Google's PAM.


sudo apt-get install libpam-google-authenticator

With the PAM installed, we'll use a helper app that got installed with the PAM to generate a TOTP key for the user you want to add a second factor to. This key is generated on a user by user basis, not system wide. This means every user that wants to use a TOTP auth app will need to log in and run the helper app to get their own key.

google-authenticator

2. Configuring OpenSSH

sudo nano /etc/pam.d/sshd
Add the following line to the bottom of the file.
@include common-password
auth required pam_google_authenticator.so nullok

The "nullok" word on the end tells PAM that this authentication method is optional. This allows users without a OATH-TOTP key to still log in using their SSH key. Once all users have an OATH-TOTP key, you can delete "nullok" on this line to make it MFA mandatory.

sudo nano /etc/ssh/sshd_config

Look for ChallengeResponseAuthentication and set its value to yes.
ChallengeResponseAuthentication yes

3. Making SSH Aware of MFA

sudo nano /etc/ssh/sshd_config
make sure
PasswordAuthentication no

add the following line at the bottom of the file. This tells SSH which authentication methods are required.


. . .
UsePAM yes
AuthenticationMethods publickey,keyboard-interactive

sudo nano /etc/pam.d/sshd
comment out
#@include common-auth

sudo service ssh restart

--------------------
If you bypass step 3, you will still be able to ssh without the code.

If you lose your secret key and the backup, use the console via the DigitalOcean control panel to log in. Then either rename or delete the file ~/.google_authenticator. This will make sure PAM is unaware of your configuration, and won't prompt you for a code. Make sure that /etc/pam.d/sshd still has "nullok" added, like in step 2; if you change this, make sure to restart SSH.