How to set up SSH keys

SSH keys are used to log in to Secure Shell, a protocol usually used for remote linux shells or SFTP (SSH File Transfer Protocol). SSH keys offer more security and user comfort than passwords.

Generating a key pair generates a public and a private key. The public key can be placed on a server, and then that server will allow users with the corresponding private key to log in without a password. You can also add a passphrase to the private key so that the private key in itself isn’t enough to enter your servers.

Step One: Create RSA Key Pair

The first step is to create the keypair: $ ssh-keygen -t rsa

ssh-keygen will ask you where you want to save the keypair. The default is fine, if you don’t have any other keys stored there. You may also choose a passphrase, if you’d like one. If you don’t have a passphrase, and someone manages to access your keyfile, they will be able to log in to your accounts where you use that key.

Step Two: Copy the public key

Once the key is generated, you have to place the public key on the machines you want to access. Next to where you stored the private key, there should be a file with the same name and a .pub suffix. You want to copy the contents of that file into the “~/.ssh/authorized_keys” directory of the accounts you want to access.

If you have ssh access with a password to a machine, you can use ssh-copy-id to automatically add the key to an account:

$   ssh-copy-id demo@10.10.0.40

Alternatively, you can paste it with ssh (this command assumes the keyfile is in the default location):

$   cat ~/.ssh/id_rsa.pub | ssh demo@10.10.0.40 "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >>  ~/.ssh/authorized_keys"

Now, try loogging into that account. You shouldn’t be asked for a password, although if your key has a passphrase you will be asked for that.

Step Four: Disable password for root login

This step is optional and should only be done if you’ve made sure that you can log in with your keyfile without using a password. It makes your server more secure, since most bruteforce attempts don’t even try to target ssh key – they are too long and complex.

To do this, login to root on the server and open the SSH config file in your preferred editor. Here, we’ll use nano:

$   nano /etc/ssh/sshd_config

If you don’t have access to the root account but your account is an admin, use sudo:

     $       sudo nano /etc/ssh/sshd_config

In that file, find the line that says PermitRootLogin and modify it so that it’s only possible to connect with an SSH key:

/etc/ssh/sshd_config
PermitRootLogin without-password

Save and close the file. To put these changes into effect, you need to reload your sshd service:

$   systemctl reload sshd.service

This requires root priveleges. If you’re not on root, use sudo again:

$   sudo systemctl reload sshd.service

Leave a Reply

Your email address will not be published. Required fields are marked *