Introduction
Normally, we only need to enter a password or use an SSH key to log in to our server remotely. In Two-factor authentication, users need to pass two authentication layers to access an account on the ubuntu system. 2FA is a time-based one-time password to log in to the ubuntu server. This one-time password is computed using the TOTP algorithm.
This article will explain how to add Public key Two-factor authentication with Ubuntu 18.04 and Ubuntu 20.04 OS.
Prerequisites
- A root or non-root user with
sudo
privileges. - A smartphone running Android or Apple iOs with the OATH-TOTP app installed.
Install Google’s PAM Package
Pluggable Authentication Module(PAM), is a mechanism that provides multi-factor authentication on the Linux platform.
- Run the following command to install Google Authenticator from the default Ubuntu package repository.
$ sudo apt install -y libpam-google-authenticator
- Then run the below command to initialize PAM and create a secret key in the home directory.
$ google-authenticator
- In the next step, scan the QR code with the Google Authenticator app. If you don’t want to scan the QR code, you can enter the secret key on the Google Authenticator app on your phone.
Configure SSH to Use Google Authenticator
- Need to configure SSH to use Google Authenticator open
/etc/pam.d/sshd
file.$ sudo nano /etc/pam.d/sshd
- To enable 2FA in SSH, do the following changes as shown in the below snippet.
a) Comment out standard Unix authentication.
b) Include a two-factor authentication configuration.
# Standard Un*x authentication.
# @include common-auth
# two-factor authentication via Google Authenticator
auth required pam_google_authenticator.so - Find out the below parameters in the
/etc/ssh/sshd_config
file and make sure both of them are set to yes.UsePAM yes
ChallengeResponseAuthentication yes - Add the below code in the
/etc/ssh/sshd_config
file to enable the public-key authentication and challenge-response authentication.PermitRootLogin yes
AuthenticationMethods publickey,keyboard-interactive - Save and close the file. Then restart the SSH daemon for the change to take effect.
$ sudo systemctl restart ssh
- Your SSH server is now configured with multi-factor authentication. On the remote system, open a terminal and log in to the server via SSH You will be asked to provide your system password and Verification code generated by Google Authenticator.