SSH keys help add a layer of security to your website. Normaly a SSH connection (Secure Shell) is between a client and a server. This connection is authenticated by a password. It is not to say that passwords are not secure anymore now a days. It is easy to bruteforce into a SSH server by trying different combinations of passwords. How long do you think it would take a hacker to try a password of 8 digits? In a super computer it would be a matter of minutes, in a normal machine using it’s GPU, a matter of days. This means passwords are a security vulnerability. But do not worry, there is a way to avoid using passwords. SSH Keys
What is a SSH Key?
A SSH Key is an encrypted key consisting of a PUBLIC KEY and a PRIVATE KEY. This method works through RSA Encryption where the public key is available to all public to encrypt data, but only the private key can decrypt that data. At least for now. You could technically decypher a private key but it would take you a couple years, a bit safer than a password. Normally we see this kind of encryption between our browser and the web. You have acces to the public key of the server, which in turn encrypts your data. But you can not decrypt it. This is called one-way encryption.
Creating a SSH Key
First you need to know if you have any keys currently generated. For this just run the following command:
ls -l ~/.ssh/id_*.pub
This will tell you if there are any currently generated keys, if the result comes back as: No data/files found then, you can use the already generated key or create your own.
Now lets generate the key with the following code:
ssh-keygen -t rsa -b 4096 -C "email@example.com"
Make sure to replace your e-mail address. Now press Enter, you will be asked to create a passphrase. This adds an extra layer of security, although it is optional. You will see the following output:
Enter passphrase (empty for no passphrase):
Your output will be similar to this one
Now you can run
The output will be
Note: Until now this has all been generated in your machine, not the server. This is important because the following command will link your user with the SSH key.
Linking Key with User
You will be prompted with the following output
Once authenticated, the content of
~/.ssh/id_rsa.pub will be copied to
~/.ssh/authorized_keys. You can equally just perform the following commands if you are unable to do the commands mentioned before.
On the server, perform this command:
cat ~/.ssh/id_rsa.pub | ssh remote_username@server_ip_address "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
Disabling SSH Login with password
ssh sudo_user@server_ip_address sudo nano /etc/ssh/sshd_config
Find the following lines and change them as follow:
PasswordAuthentication no ChallengeResponseAuthentication no UsePAM no
sudo systemctl restart ssh
You are good to go now.