- Make logging in faster
- Scripting and automation
- Part of mult-factor authentication
Before we go any further, log into your SSH server to make sure it is configured to allows key based authentication.
$ ssh myaccount@server $ cat /etc/ssh/sshd_config | grep AuthenticationMethods
The default configuration for SSH servers is for that command to return nothing, which means key based authentication is enabled. If it returns publickey, it will also work. There may be other values included in the line. If they are separated by a comma, then they require multi-factor authentication. If they are separated by a space, they can be used for single-factor authentication.
In order to make things work, you need to generate a key-pair for your user account on the endpoint (client) you are going to connect from. Then, you need to put the public key from that key-pair onto the system where you are logging in using SSH (server). If you want to have multiple different users be able to log in using keys, you need to repeat this process for each of them. Let's walk through it.
Start by generating the key-pair using your account on the client system. You can adjust the options here depending on how strong of a key you want to use. I'm going to use the strongest possible key that is supported at this time.
$ ssh-keygen -b 521 -E sha256 -o -t ecdsa
Let's have a look at where the new keys are stored
$ ls -l ~/.ssh/ total 16 -rw------- 1 myaccount myaccount 736 Feb 6 15:33 id_ecdsa -rw-r--r-- 1 myaccount myaccount 268 Feb 6 15:33 id_ecdsa.pub -rw------- 1 myaccount myaccount 1386 Feb 8 20:46 known_hosts
In this case, id_ecdsa is my private key. Notice how only myaccount has access to them. The public key is id_ecdsa.pub and anyone can read it. Next, you'll have to get a copy of the public key over to the SSH server and store it in the home directory for the user account you'll be logging into. We can use scp to get the file copied over.
$ scp ~/.ssh/id_ecdsa.pub myaccount@server:~/
This will place the public key in the home directory of your account on the SSH server. For the next part, you'll have to connect to the SSH server.
$ ssh myaccount@server
Copy the public key to the end of the authorized_keys file for the account. Note the use of the double carrot (>>) here. A single carrot (>) will overwrite the file if it already exists. A double (>>) carrot will add text to the end of the file if it already exists. Either way will create the file if it does not already exist.
$ cat id_ecdsa.pub >> ~/.ssh/authorized_keys
Now you're all set. Log out of your SSH session and then log back in. When you reconnect, it should authenticate with your key-pair and not prompt for a password (unless the server is configured to use multi-factor authentication).
Post a Comment