SSH authentication with keys
The SSH protocol (Secure SHell) is an encrypted protocol used to establish secure connections between two machines: customer e server. By itself it's already a pretty secure protocol, but with SSH keys you can close SSH access to only specific machines. Here's how.
In this mini-guide we will see how to set up an SSH access to a machine “server” by authenticating without a password. With this configuration only those with the right SSH keys will be able to access the server. In this example we will use the following IP addresses:
- Client: 192.168.5.114
- Server: 192.168.5.10
One of the fundamental requirements is that the user who generates the SSH key has an account enabled and belongs to the group
sudoers on both machines.
Generate the key on the server
First we generate the SSH key on the server. Log in to the server (either directly or via traditional SSH) and run this command.
~$ ssh-keygen -t rsa
While the key is being created we will have the option to associate or not a password. I recommend associating the password unless there are particular impediments such as having to disable the password at login. In any case we will have two possibilities both safe.
Copy the key to the client
Once the command is complete we will have to launch another one to copy the generated key to the client.
~$ ssh-copy-id -i $HOME/.ssh/id_rsa.pub USER@192.168.5.114
USER is the user registered on the client that we will use to log into the server.
I assume that these operations are performed within a LAN, but if this is not the case, it is necessary to find a way to copy the key generated in
~/.ssh/id_rsa.pub in the client in use via for example an FTP share, an email or even un wormhole.
Test the connection
Eventually it will be time to test the actual functioning. We go back to the client and launch the command:
~$ ssh -v USER@192.168.5.10
USER is the user listening on the server.
If we have configured the SSH key without a password we will be immediately logged into the server, on the contrary if we have set a password to the key, this will be required now.
Disable user password authentication
If we have successfully logged into the server we may want to configure access not to accept connections via user password. Open the file
/etc/ssh/sshd_config with an editor and add a line to the bottom of the file as follows:
We restart the SSH service:
~$ sudo service ssh restart
Now if we try to log back into the server we won't be able to do it without the generated SSH key. Once we are sure that everything is working properly we can share the key (using the command
ssh-copy-id dal server) with the users we want to grant access to.
If the only way to access the server is via SSH, be careful not to lose the keys, or we will not be able to enter the car.