Image

Knowledge base → Setting up two factor authentication in ssh for root on Debian 12

[Virtual servers]
Date of publication: 05.10.2023

To set up two factor authentication for the root user, we will use Google Authenticator. This application is available on all platforms and is time dependent. Thus, even if access to Google services is impossible, the main thing is that the time is synchronized, then everything will work correctly.

In our example, we will make sure that a standard user logs into ssh using a password as usual, but when trying to escalate privileges to the root user using the su - command, first the password is required and then the code from the Google Authenticator application.

At the same time, we will prohibit logging into ssh as the root user in order to force the use of two-factor authentication for this user.

1. Let's install the necessary packages:

apt install libpam-google-authenticator

2. Let's make the first setup:

./google-authenticator

2.1 As a result, you will be prompted to enter the code from the application, as an alternative to the google application, you can use FreeOTP.

2.2 Set up the SSH service:

nano /etc/ssh/sshd_config

PermitRootLogin no
UsePAM yes
ChallengeResponseAuthentication yes

Let's restart the service for the settings to take effect:

systemctl restart ssh

2.3 Set up a code request after entering the password for the su command -

Let's add lines so that the file looks like this:

nano /etc/pam.d/su
...
auth sufficient pam_rootok.so
...
auth required pam_unix.so no_warn try_first_pass
auth required pam_google_authenticator.so
...

3. Done, you can check the operation, after logging in as a normal user and trying to switch to root using the su command, after entering the password, you will be prompted for a code from the application.


Also:

3.1 If you want to prompt for code when trying to connect to ssh, then you will need to add these lines to the file:

nano /etc/pam.d/sshd
...
@include common-auth
...
auth required pam_unix.so no_warn try_first_pass
auth required pam_google_authenticator.so
...

If you are using the root user, allow login in the ssh settings; if you are using another user, run the command:

./google-authenticator

as a regular user and configure it in the same way as we described for the root user.





No Comments Yet