SSH supports authenticating users with keys. Although they require more setup ahead of time, they’re generally more secure than typing in passwords. They’re also more convenient in the long run. In this article, I am going to cover using key-based authentication in OpenSSH.
Installing SSH Keys
When we ran
ssh-keygen, the program created key pairs which are saved in
~/.ssh/id_* format. To be able to use key-based authentication, the public key i.e. the one with the
.pub extension need top be installed in the
~/.ssh/authorized_keys file of our SSH server. And that’s really all we need to do. It doesn’t matter how we do it, but the contents of our public key need to be there.
Now the first approach would be a bit more manual. We send the contents of the file and pipe it to the server at the other end like so:
cat ~/.ssh/id_*.pub | ssh user@host 'cat >> ~/.ssh/authorized_keys'
Now the standard installation of OpenSSH automatically included a script make this more convenient.
All we need to make sure now is that we have the corresponding private key of those installed public key files. The private keys are called Identity File in ssh-terminology.
With key based authentication, the only security we have is that our identity file is safe with us. If it gets compromised, then we’re doomed.
So, why don’t we encrypt it with a password? That would be great. In fact, we should do that.
Specify a passphrase at the
Note: A passphrase is a series of random works like “correct horse battery staple“. Passphrases are easier to remember than traditional passwords but are considered equally (perhaps more) secure. We should use them.
However, this again brings us the hassle of typing in our passphrase every time we need to
ssh into a server. Eventhough our password only travels locally making it still more secure, it’s nevertheless still inconvenient.
ssh-agent comes in.
ssh-agent runs in the background and handles the passphrases for you. The way this works is, you run
ssh-agent which gives us some environment variables that will later be used by our
ssh client. We then run
ssh-add which decrypts our private key file (it asks for the passphrase at that time) and then it adds that key file to the ssh agent. This way, our decrypted private key is only loaded into memory. You can of course never use
ssh-agent if having private keys in memory doesn’t suit your threat model.
ssh-agent(1) manual page describes some of the ways we can run that program. Most desktop environments should automatically handle this. Nonetheless, this is how I do it (since I also start my desktop using the traditional
I launch the
ssh-agent when I login so that the environment variables are inherited by other processes. Since I use
zsh as my login shell, I have the following in my
And that’s basically it. Now we can disable password authentication in our