So you’ve got yourself a nice fancy server running Linux, but you want to make sure access to your server is secure as possible. What do you do? Easy – configure your server to use key-based authentication.
First off, you need to generate yourself a keypair. Each computer that you will use to access your server should have it’s own keypair – this makes it easy to limit access should your computer be compromised at some point. Fire up a terminal and type the following:
ssh-keygen -t rsa -b 2048
This will generate an RSA based key with 2048 bit encryption. For the most simple operation, accept the defaults through the generation process. When you are asked for a passphrase, you should input a highly secure password – no common words, patterns, names, etc.
This will create two files in the .ssh directory in your home folder: id_rsa and id_rsa.pub. id_rsa must be kept secret – do not distribute this file.
Once the files are generated, you will need to copy your public key to the remote server. The SCP binary is awesome for this:
scp ~/.ssh/id_rsa.pub [email protected]:~/.ssh
This will copy the public key file to your remote server’s user account in the .ssh directory under your home folder. You should be prompted for a password before the transfer is complete.
Once the transfer is complete, you will want to add the key to your authorized_keys file. Most distributions will not have this file in the .ssh directory by default, so we will need to add it after we log in:
ssh [email protected] cd ~/.ssh
First, we want to see if the authorized_keys file exists:
If you do not see authorized_keys or authorized_keys2, then let’s create them. Which file you need depends on your operating system and many other factors, so we’ll account for both here. If you already have an authorized_keys file, skip to line 3:
touch authorized_keys ln -s authorized_keys authorized_keys2 chmod 600 authorized_keys cat id_rsa.pub >> authorized_keys
We now need to configure the SSH server to allow key based authentication. Debian-based distros have the configuration file at /etc/ssh/sshd_config. Your distro may be different, so you may need to consult documentation. I use vi myself, you can substitute vi for your favorite text editor:
sudo vi /etc/ssh/sshd_config
Find the following lines and ensure they say Yes:
RSAAuthentication yes PubkeyAuthentication yes
Save the file, exit your editor, and then restart the sshd service:
sudo /etc/init.d/ssh restart (OR sudo service ssh restart)
Fire up another shell, and attempt to SSH to your server again:
You should be prompted for your passphrase, but not your account password on the remote server. If you are not prompted for your account password, make sure you modify the following line in your ssh configuration file to disable clear-text password logins:
Restart ssh again, and you’re good to go!