Sunday, January 23, 2011

Setting up public key authentication for SSH

If you're like me, you remote into a handful of servers using SSH all the time. The process is fairly simple:

  1. Get to a terminal
  2. ssh username@hostname
  3. Type password
  4. Get to work

No, it's not terribly difficult, but when you have to type that password fifty times per day, you begin to realize that it's time-consuming and repetitive. And there happens to be a way to eliminate that step from the process.

The SSH protocol supports authentication by public keys, and setting this up is a trivial matter. The configuration process goes something like this:

  1. Generate a key for your client system
  2. Put it on the server

One prerequisite: your SSH server must have public key authentication enabled. This is usually the case by default, but if you want to check, you can look in your /etc/ssh/sshd_config file. Try this:

grep 'PubkeyAuth' /etc/ssh/sshd_config

If the output is

PubkeyAuthentication yes

then you're safe to continue. Otherwise, you'll have to make the change in that file and restart the SSH server. There are a few ways to accomplish this, and I won't go into them here because it's not the point.

The point is that once this is ready, you can create your RSA key on the client machine. This is the first step toward getting this done. On the client machine, run

ssh-keygen -t rsa

You'll be asked for a filename. Just press enter to accept the default, which is probably ~/.ssh/id_rsa

You'll also be asked for a passphrase. You can use this optionally. If the point is to eliminate having to enter a password with every SSH connection, it's best to supply no passphrase. You'll also be asked to confirm it.

When done, you'll get a printout of your fingerprint and you'll return to a prompt.

Now we need to check this file's permissions. We don't want any other users to be able to read this pubkey file lest they compromise your authentication.

chmod 600 ~/.ssh/

EDIT: Commentor FKereki rightly points out a simpler and better way to accomplish the publication of your public key to your server. You can (and should) run:

ssh-copy-id username@hostname

This command makes sure that the pubkey is added to the appropriate file, and it makes sure nothing gets lost. This is the best possible way to accomplish this task if the command is available to you. However, should you be working in a system where this isn't available (such as a Solaris environment), you can use the following steps to make things work.

Copy your public key to the server as a specific filename.

scp ~/.ssh/ username@server:~/.ssh/authorized_keys

Make sure the authorized_keys file has the same permissions so it won't be compromised.

The next time you log in from this client machine, you won't be asked for your password.