Wednesday, December 15, 2010

SSH keys in 3 Commands

SSH keys are useful for accessing machines over SSH without having to type your password every time. I'll be discussing a method here that uses a SSH agent, which is arguably more secure than using a blank password for your key. Also, I assume you're running a bash-like shell. The "server" is the machine you want to connect to and the "client" is the machine you'll be connecting from.

What to run:
1) you@client$ ssh-keygen -t rsa -f ~/.ssh/id_rsa
2) you@client$ cat ~/.ssh/id_rsa.pub | ssh YOU@SERVER.ORG "mkdir -p ~/.ssh; cat - >> ~/.ssh/authorized_keys"
3) you@client$ source <(ssh-agent) && ssh-add ~/.ssh/id_rsa
Now, when you ssh YOU@SERVER.ORG, you should not be prompted for a password. You will need to rerun step 3 each time you open a new terminal or use your window manager to

What these do:
1) Creates a new public/private RSA keypair. The private key (id_rsa) will always stay on your computer. The public key will be copied to servers you wish to access. I recommend using a strong (that definitely means non-blank) password.
2) This *appends* your new public key to the list of keys that are allowed to access the machine (a magic file, which sshd always looks for in ~/.ssh/authorized_keys). If we had just used scp to copy the file here, we could have overwritten other keys that are allowed to access the machine.
3) This first starts the ssh-agent program, which returns some bash commands to stdout to initialize environment variables. By enclosing this in a process substitution and passing the result as a "file" to source, this stdout is executed as commands in the current shell. Finally, it adds your private key to the ssh-agent so that it will be passed to remote hosts you try to login to.

To keep things secure, it is important to remember that this key be kept secure. That means:

1) You should set permissions so that only you can read from the key (chmod o-rwx ~/.ssh/id_rsa)
2) You should never place your host keys on an insecure filesystem. This isn't as obvious as it sounds. Network filesystems such as AFS and NFS are apt to passing files that can "only be read by you" according to their permissions over the network unencrypted so that anyone who can sniff the network traffic can acquire your key. Be sure to keep your keys on a local filesystem.

NOTES:
Many modern servers now use Kerberos via GSSAPI for authentication. If your server is using Kerberos for authentication, the method here may either 1) not result in you being able to login without a password or 2) result in you being able to login, but then getting strange security errors when trying to access filesystems such as AFS or NFS4 or resources such as Hadoop MapReduce.