Vaibhav Singh

Blog - vaibhavsingh.com

Protect SSH with TOTP 2FA

A few of my compute nodes running on AWS were required to have their SSH port open to the public internet. There are several well established ways that can be used to protect the login. Fail2ban comes to mind, or a firewall if you know the source IP addresses or the range.

In this instance, I decided to use time-based one time password based two factor authentication.

Create a new SSH user

sudo adduser user1

Add to sudoers group if needed.

sudo usermod -aG sudo user1

Modify SSHD configuration file.

sudo nano /etc/ssh/sshd_config

ChallengeResponseAuthentication yes # CHANGE THIS TO YES
#PasswordAuthentication yes # COMMENT IT OUT

Install 2FA libraries and edit configuration file.

sudo apt install libpam-google-authenticator
sudo nano /etc/pam.d/sshd

#Add the following lines as the last line

   # Custom addition for Google 2FA
   auth required pam_google_authenticator.so

Now sudo su to the new user we created earlier and generate 2FA codes.

sudo user1
google-authenticator

Do you want authentication tokens to be time-based (y/n) y
Do you want me to update your "/[...]/.google_authenticator" file? (y/n) y
[...]your chances to notice or even prevent man-in-the-middle attacks (y/n) y
[...]Do you want to do so? (y/n) no
[...]Do you want to enable rate-limiting? (y/n) yes


#Restart the sshd daemon using

sudo systemctl restart sshd.service

Everything should be ready to go at this point from the server end. Next step is to configure the app on your phone.

Add the entry to Google Auth App

Upon executing the google-authenticator command and answering the questions, it will present a QR code which can be scanned using the Google Auth app on your phone. Make note of the temp scratch codes. These are one time use codes, required for recovery.

Testing

Now, open a SSH session using PuTTY, it will ask you for your password first and then the OTP code.

Reference

Refer to the documentation [here] for further information.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top