Typically, we only need to enter a password or use an SSH key to log in to our server remotely. In Two-factor authentication, users must pass two authentication layers to access an account. 2FA is a time-based one-time password to log in to the server. This one-time password is computed using the TOTP algorithm.
This article will explain, How to add public key Two-factor authentication with CentOS 7 and CentOS 8.
- A root or non-root user with
- 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.
- PAM package is available via EPEL repository. We can install it with the below command.
# sudo yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
- Next, install the Google Authenticator(PAM) for multi-factor authentication using the below command.
# sudo yum install google-authenticator
- Then run the below command to initialize PAM and create a secret key in the home directory.
- 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 Once it’s added, you’ll see a six-digit code that changes every 30 seconds in your app.
Configure SSH to Use Google Authenticator
- Need to configure SSH to use Google Authenticator open
# 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.
# two-factor authentication via Google Authenticator
auth required pam_google_authenticator.so
- Find out the below parameters in the
/etc/ssh/sshd_configfile and make sure both of them are set to yes.
- Add the below code in the
/etc/ssh/sshd_configfile to enable the public-key authentication and challenge-response authentication.
- Save and close the file. Then restart the SSH daemon for the change to take effect.
# sudo systemctl restart sshd.service
- 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.