Skip to content

Two-factor SSH authentication

Two-factor authentication adds an additional layer of security by requiring not only a password but also a physical device or information that is more difficult for a malicious actor to obtain. This significantly increases security because even if an attacker manages to learn or steal your password, they will still need additional information for successful authentication. By setting up two-factor authentication for SSH connections, you significantly increase the security of your server.

Setting up two-factor authentication for SSH connections is very simple. Connect to your virtual or dedicated server via SSH and install the package:

sudo apt-get install libpam-google-authenticato

Configure the SSH server to work with two-factor authentication. Add the following line to the sshd file:

auth required pam_google_authenticator.so

And in the sshd_config file, add the following line:

ChallengeResponseAuthentication yes

And in the sshd_config file

nano /etc/ssh/ sshd_config

Add a line


Setting up two-factor authentication for a user

Log in to the system as the user for whom you want to set up two-factor authentication in SSH.

To set up two-factor authentication, run the command:


After running the command, a QR code will be generated in the terminal that you need to add to the application, or you can use the secret key listed below the QR code.

Then follow the prompts of the program and complete the setup.

Now we can restart the SSH server and try to connect as the user for whom we set up two-factor authentication.

service sshd restart

Connect to the server as the user for whom we set up two-factor authentication and now before entering the password we will need to enter the code, and only then the password.

Important note! If you have set up user login via SSH key, two-factor authentication will not be applied.