SSH using keys
What are SSH Keys?
By using SSH Keys (a public and private key to be precise), you can easily connect to a server, or multiple servers, without having to enter your password for each system.
It is possible to setup your keys without a passphrase, however that is unwise as if anyone gets hold of your key they can use it. This guide describes how to setup your system so that passphrases are remembered securely.
Generating SSH Keys
The keys can then be generated by running the ssh-keygen command as a user:
# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
45:54:10:01:9d:ef:a3:34:a6:d9:f3:a2:41:e3:87:b7 root@localsquid
It will prompt you for a location (which you should leave as the default), however the passphrase is the important bit! I hopefully need not tell you the rules of a good passphrase?
Default key length for RSA is 2048 and is sufficient.
Copying the keys to the remote server
Now you have generated the keys you need to copy them to the remote server. By default, for OpenSSH, the public key needs to be concatenated into ~/.ssh/authorized_keys.
# scp ~/.ssh/id_rsa.pub root@192.168.1.100:
This copies the public key (id_rsa.pub) to your remote server via scp (note the : at the end of the server address). The file ends up in the home directory, but you can specify another path if you like.
Next up, on the remote server, you need to create the ~/.ssh directory if it doesn’t exist and concatenate the key authorized_keys file:
# ssh root@192.168.1.100
root@192.168.1.100's password:
# mkdir ~/.ssh
# cat ~/id_rsa.pub >> ~/.ssh/authorized_keys
# rm ~/id_rsa.pub
# chmod 600 ~/.ssh/authorized_keys
The last two commands remove the public key from the server (which isn’t needed now), and sets the correct permissions on the authorized_keys file.
If you now disconnect from the server, and attempt to reconnect, you should be asked for the passphrase of the key (if any):
# ssh root@192.168.1.100
Enter passphrase for key '~/.ssh/id_rsa':
If you are unable to login with the key, double check the permissions on the authorized_keys file.
Also check the permissions on the ~/.ssh directory, which should have write permissions off for ‘group’ and ‘other’. Run the following command to disable ‘group’ and ‘other’ write permissions for the ~/.ssh directory:
# chmod go-w ~/.ssh