torsdag 27 oktober 2016

Two-factor authentication part 2 - 2FA with SSH

On any linux based server, it is possible to protect SSH with two-factor authentication using the Google Authenticator PAM module. This is actually easy to install and configure.

Login to your SSH server and install the module.

On Debian (or for instance Raspbian):
sudo apt-get install libpam-google-authenticator
On Fedora:
dnf install google-authenticator

Create the verification key for the user. I prefer to not allow root access to a server, so this step should be run as the user that should be able to login:
google-authenticator
You can answer y to most questions. Finally, you will get a QR code that can be scanned by your phone TOTP app (any standard TOTP application will do). Make sure to store the emergency codes in a safe place, such as a Keepass database or on a paper.

Now you need to make a few changes, so that PAM (which is responsible for authentication on most linux systems) asks for the verification code in addition to your password when logging in through SSH.

Edit the PAM config file for sshd:
sudo nano /etc/pam.d/sshd
 Add the following row to the top of the file:
auth required pam_google_authenticator.so
Edit sshd config:
sudo nano /etc/ssh/sshd_config
Change the following option to yes if it is set to no:
ChallengeResponseAuthentication yes
This will allow the sshd daemon to ask for other things than only the password, such as asking for the additional verification code that we added to the PAM configuration.

You can check sshd_config after any change with the following command:
sudo sshd -t
This will show any error in the sshd configuration and prevent you from being unable to connect to the server. Still, keep an additional terminal open to the server while doing any sshd or authentication changes.

Finally restart the sshd service:
sudo systemctl restart sshd.service
or on older systems:
sudo service sshd restart

Finished! Now you will be asked for the verification code when logging in through SSH in addition to your password.