September 12, 2016

ssh keys

I am always forgetting how to set up SSH keys, so here is my cheat sheet.

Let us say we have 2 machines, "home" and "work" and we want to be able to use keys to login from "home" to "work".

First, on both machines do "ssh anywhere" (where "anywhere" would typically be the name of the other machine, but could be any machine at all) and use your password. This will guarantee the .ssh directory will be created with proper permissions and should create the known_hosts file in it. Or to set proper permissions, chmod 700 .ssh seems to do the job.

Now create the keys (this can take a while on a slow machine). These days you want to generate RSA keys (As of mid 2016 DSA keys are no longer accepted by default by OpenSSH). You can real endless discussions online about which is better and why: Do this on the home machine:

ssh-keygen -t rsa -b 4096
Unless you get the bright idea of having it use a different filename, this creates id_rsa and id_rsa.pub.
id_rsa stays on the home machine (this is your private key), and you distribute id_rsa.pub to any machine you want to login to.

If you DO give it a unique name (such as hoseclamp_rsa) you will need to rename the private key to id_rsa on the local machine. You can then distribute the public key as hoseclamp_rsa.pub. A scheme like this does make some sense if you have accounts on lots of machine.

Distribute the public key by appending it to .ssh/authorized_keys. I usually use scp to copy it there as id_rsa.pub and then use an editor to append it. Just copying it directly to the authorized_keys file is not a good idea as it will overwrite any other public keys already contained there.

The permission on authorized_keys must be 644.

Notice that in July of 2012, the Fedora distribution of ssh began shipping configured to use "authorized_keys" rather than "authorized_keys2".

You have to cope with giving the passphrase (unless you didn't give one when you ran ssh_keygen, which is not a good plan). A recommended way is to use a key_agent:

ssh-agent sh -c 'ssh-add </dev/null && bash'

Much of this came from this link: how to set up SSH keys

Once this is set up, you can do cool things like tar backups across the network like so:

cd /xyz ; tar cf - . | ssh machine "dd of=xyz.tar"

Doing this with cat gets into weird issues with the redirection arrow, and you end up with a local copy or some confusing complaint about a pseudo terminal, using dd works fine.


Feedback? Questions? Drop me a line!

Adventures in computing / tom@mmto.org