Rather than using a username password based SSH login, it is much safer to use SSH certificates as those have an (ideally very close) expiration date. The first step to use public key authentication is to generate a keypair.
andreas@laptop ➜ ~ ssh-keygen -t ecdsa -f ~/.ssh/id_ecdsa
Above command will generate a keypair using an elliptic curve digital signature algorithm. You will be asked to type a passphrase for protection of your private key. You should definitely use a passphrase. Do not leave your key unprotected!
andreas@ laptop ➜ ~ ls -l ~/.ssh/ total 144 -rw------- 1 andreas staff 578 Dec 10 10:47 id_ecdsa -rw-r--r-- 1 andreas staff 193 Dec 10 10:47 id_ecdsa.pub
In a next step you can submit id_ecdsa.pub – the public part of the key, to your SSH CA for obtaining a signed certificate. Anyway, this step is optional. What you will need to do is to create a config file for ssh that dictates when and how to use the key.
andreas@laptop ➜ ~ vim ~/.ssh/config
Now add the following content to ~/.ssh/config and save it.
Match Host *.local UseKeychain yes AddKeysToAgent yes Preferredauthentications publickey IdentityFile ~/.ssh/id_ecdsa # user andreas
Here is what the configuration does on a line by line basis.
- a host filter that says apply to block of setting below for every host that ends with .local (i.e.: server1.local, server23.local, …)
- advice the ssh agent to use OSX’s keychain
- advice the ssh agent to upload private keys into OSX’s keychain once they have been unlocked
- use public key authentication
- use the private key stored in ~/.ssh/id_ecdsa for public key authentication to hosts with hosts
- optional: always use andreas as a username so rather than ‘ssh andreas@host1.local‘ you only have to type ‘ssh host1.local‘
Finally you need to perform an initial upload of your key into OSX’s keychain (this is a one time thing!).
andreas@laptop ➜ ~ ssh-add -K ~/.ssh/id_ecdsa
After you have done this, you can login to any host that trusts you without unlocking your private key with your passphrase as long as you don’t reboot your PC.
