Enabling Certificate-based Login
To use a private key for SSH login on CentOS, you’ll need to complete the following steps:
-
Generate an SSH key pair: Use the
ssh-keygen
command to create a key pair. There are various methods for generating keys, including using PuTTY, Xshell, and MobaXterm, which all have built-in key generation features. For example, you can enter the following command and follow the prompts:1
ssh-keygen -t rsa -b 4096
-
Add the public key to the authorized keys list on the target server: Copy the contents of your generated public key into the
~/.ssh/authorized_keys
file on the target server. Essentially, you will renameid_rsa.pub
toauthorized_keys
. -
Configure the SSH service to use key-based authentication: To do this, modify the SSH configuration file located at
/etc/ssh/sshd_config
and enablePublic Key Authentication
by setting the parameter to “yes”. -
Restart the SSH service: After updating the SSH configuration, restart the
sshd
service to apply the changes. You can use the following command to restartsshd
:1
systemctl restart sshd
-
Store the private key file on the client machine: On the machine that will be used to log into the target server, save the certificate file in the user’s SSH folder (by default, this is
~/.ssh
). -
Connect to the target server: Use a command similar to the following to log into the target server:
1
ssh -i /path/to/private_key user@server_ip
Here,
/path/to/private_key
is the path to your certificate file,user
is the username, andserver_ip
is the IP address of the target server.
Restricting Login to Certificate Only
As mentioned earlier, we can enable certificate-based login. But how can we disable password authentication and allow only certificate-based login?
In CentOS, you can restrict login to certificate-based authentication by modifying the SSH service’s configuration file /etc/ssh/sshd_config
. Here are the steps to do this:
-
Log into the CentOS server using the root user.
-
Open the SSH configuration file at
/etc/ssh/sshd_config
, and locate the following two lines:1 2
#PubkeyAuthentication yes #PasswordAuthentication yes
-
Remove the comment symbol
#
from the line#PubkeyAuthentication yes
, and changeyes
toonly
, so it looks like this:1
PubkeyAuthentication yes
This configuration means that only public key (certificate) authentication will be accepted, and password logins will not be allowed.
-
Remove the comment symbol
#
from the line#PasswordAuthentication yes
and changeyes
tono
, so it looks like this:1
PasswordAuthentication no
This configuration will prohibit password-based authentication.
-
Save and close the file.
-
Restart the SSH service to apply the changes. You can restart the SSH service using the following command:
1
systemctl restart sshd
Once the setup is complete, only users with the corresponding private key (certificate) will be able to log into the CentOS server. If a user does not possess the appropriate private key, they will not be able to log in.