To secure a Linux server, disable password authentication on it. This way only those users can connect to it, who have access to an authorized private key.
To enable users to connect to a Linux server with a private-public key pair
Generate an RSA key pair
- In a Bash terminal on your workstation execute
ssh-keygen
- Follow the prompts to specify the name of the key file pair. In most of the cases, you don’t need to protect the key with a password.
- If you don’t specify the file name, the key will be saved as ~/.ssh/id_rsa
- If you specify a file name, the key files will be saved in the current directory
- The public key file will get the “.pub” extension, the private file has no extension
Upload the public key to the Linux server
- Log into the server with the “ssh” command using a username and password
ssh MY_USER_NAME@SERVER_IP_ADDRESS
- Add the public part of the key to the user configuration
- Switch to sudo mode, this command will ask for the password again
sudo -i
- Navigate to the user home directory
cd /home/USER_NAME/
- Add the public key to the user’s authorized_keys file. Open the file with a text editor and copy the public key into a new line.
vi authorized_keys
- To test the configuration, on your workstation navigate to the directory where the new key is located, and log into the server with
ssh -i MY_KEY_NAME MY_USER_NAME@SERVER_IP_ADDRESS
- Switch to sudo mode, this command will ask for the password again
Turn off password authentication
- Make sure you can log in with the new key !!!
- Execute the command
sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config