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-keygencommand 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:1ssh-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_keysfile on the target server. Essentially, you will renameid_rsa.pubtoauthorized_keys. -
Configure the SSH service to use key-based authentication: To do this, modify the SSH configuration file located at
/etc/ssh/sshd_configand enablePublic Key Authenticationby setting the parameter to “yes”. -
Restart the SSH service: After updating the SSH configuration, restart the
sshdservice to apply the changes. You can use the following command to restartsshd:1systemctl 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:
1ssh -i /path/to/private_key user@server_ipHere,
/path/to/private_keyis the path to your certificate file,useris the username, andserver_ipis 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 changeyestoonly, so it looks like this:1PubkeyAuthentication yesThis 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 yesand changeyestono, so it looks like this:1PasswordAuthentication noThis 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:
1systemctl 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.