Securing SSH with ssh keys
In this article I’m going to describe how to secure a SSH server, so that it will only accept logins with ssh keys.
Generate a set of personal ssh keys
If you have already done this, you can skip this step.
$ ssh-keygen
The output should look like this.
Generating public/private rsa key pair.
Enter file in which to save the key (/home/pfarmer/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/pfarmer/.ssh/id_rsa
Your public key has been saved in /home/pfarmer/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:iHjXjogLDiwNmy3NMc1woBAnGW9ywvUrpy/h/d6RqR8 pfarmer@server
The key's randomart image is:
+---[RSA 3072]----+
|=+o. |
|+=... |
|+.= .. |
| = * ..o |
|. +.=oo S |
|.O *+o o o |
|B.B.+ . .E |
|+o +.. o o |
| .. ..o+.o |
+----[SHA256]-----+
Copy your public key to the server
You now need to copy your public key (~/.ssh/id_rsa.pub) to the server, and put it in ~/.ssh/authorized_keys, fortunately there is a handy script to help you do this, ssh-copy-id.
ssh-copy-id username@servername
You will be prompted to enter you password, once you have entered it correctly, ssh-copy-id will copy your public key to the server. You should now be able to login to the server with your ssh key, instead of your password, you will now be asked for the passphrase of your ssh key, you can of course setup ssh-agent, so you don’t need to type your ssh key each time.
Update /etc/ssh/sshd_config
Now we make some changes to /etc/ssh/sshd_config, the changes disallow password authentication, and we do a number of other things as well.
Find and change the following lines;
PermitRootLogin yes
PasswordAuthentication yes
to
PermitRootLogin no
PasswordAuthentication no
Once those changes have been made, you need to restart sshd.
$ sudo systemctl restart ssh